from netforce.access import get_active_user, set_active_user
from netforce.model import Model, fields, get_model
from netforce.database import get_connection


class ShareLocation(Model):
    _name="clinic.share.location"
    _transient=True
    _select_patient=None
    
    _fields={
        'patient_id': fields.Many2One("clinic.patient","Patient",required=True),
        'location':  fields.Char("Location"),
        "loc_select": fields.Selection([],"Select Location"),
    }

    def get_location_user(self,patient_id=None,patient_only=False):
        user_id=get_active_user()
        user=get_model('base.user').browse(user_id)
        department=user.department_id
        loc=[]
        if department and not patient_only:
            loc.append(department.code)
        if patient_id:
            patient=get_model('clinic.patient').browse(patient_id)
            self._select_patient=patient.id
            department=patient.department_id
            loc.append(department.code)
        return loc

    def default_get(self,field_names=None,context={},**kw):
        refer_id=context.get("refer_id")
        patient_id=None
        location=''
        if refer_id:
            patient_id=int(refer_id) 
            patient=get_model('clinic.patient').browse(patient_id)
            location=patient.location or ''
            uloc=self.get_location_user(patient.id)
            new_loc=[]
            for loc_code in location.split(","):
                if loc_code in uloc:
                    continue
                new_loc.append(loc_code)
            location=','.join(new_loc)
        res={
            'patient_id': patient_id,
            'location': location,
        }
        return res

    def get_location(self,context={}):
        user_id=get_active_user()
        uloc=self.get_location_user(self._select_patient)
        set_active_user(1)
        res=get_model("clinic.department").search_read([],["code","name"])
        set_active_user(user_id)
        return [(r["code"],'%s [%s]'%(r['name'],r["code"])) for r in res if r['code'] not in uloc]
    
    def onchange_location(self,context={}):
        data=context['data']
        location=data['location'] or ''
        location=location.split(",")+[data['loc_select'] or '']
        sloc=list(set(location))
        data['location']=','.join([loc for loc in sloc if loc])
        return data

    def do_share(self,ids,context={}):
        obj=self.browse(ids)[0]
        patient=obj.patient_id
        uloc=self.get_location_user(patient.id,patient_only=True)
        new_loc=uloc
        for loc_code in obj.location.split(","):
            if not loc_code:
                continue
            res=get_model('clinic.department').search([['code','=',loc_code]])
            if not res:
                raise Exception("Department code %s not found!"%(loc_code))
            new_loc.append(loc_code)
        main_loc=patient.department_id.code
        if main_loc not in new_loc:
            raise Exception("Can not delete main department %s"%(main_loc))
        #TODO check user location
        location=','.join(new_loc)
        db=get_connection()
        db.execute("update clinic_patient set location=%s where id=%s",location,patient.id)
        return {
            'next': {
                'name': 'clinic_patient',
                'mode': 'form',
                'active_id': patient.id,
            },
        }
    
    def do_clear(self,ids,context={}):
        obj=self.browse(ids)[0]
        obj.write({
            'location': '',
        })
        return {
            'next': {
                'name': 'clinic_share_location',
                'mode': 'form',
                'active_id': ids[0],
            },
        }

ShareLocation.register()