from datetime import datetime, timedelta
from netforce.model import Model, fields, get_model

FMT_DATE="%Y-%m-%d"
FMT_DATETIME="%Y-%m-%d %H:%M:%S"
DAY_TO=1

class ScheduleCopy(Model):
    _name="clinic.schedule.copy"
    _transient=True

    _fields={
        "schedule_id": fields.Many2One("clinic.schedule","Schedule",on_delete="cascade"),
        'date_from': fields.Date("From", required=True),
        'date_to': fields.Date("To", required=True),
        'mon': fields.Boolean("Monday"),
        'tue': fields.Boolean("Tuesdays"),
        'wed': fields.Boolean("Wednesdays"),
        'thu': fields.Boolean("Thursdays"),
        'fri': fields.Boolean("Fridays"),
        'sat': fields.Boolean("Saturday"),
        'sun': fields.Boolean("Sunday"),
    }

    def _get_schedule_id(self,context={}):
        schedule_id=context.get("refer_id")
        if not schedule_id:
            return None
        return int(schedule_id)
    
    def _get_date_from(self,context={}):
        date_from=datetime.now().strftime("%Y-%m-%d")
        schedule_id=context.get("refer_id")
        if schedule_id:
            schedule=get_model("clinic.schedule").browse(int(schedule_id))
            date_from=datetime.strptime(schedule.date,FMT_DATE)
            date_from=(date_from+timedelta(days=1)).strftime("%Y-%m-%d")
        return date_from

    def _get_date_to(self,context={}):
        date_to=(datetime.now()+timedelta(days=8)).strftime("%Y-%m-%d")
        schedule_id=context.get("refer_id")
        if schedule_id:
            schedule=get_model("clinic.schedule").browse(int(schedule_id))
            date_to=datetime.strptime(schedule.date,FMT_DATE)
            date_to=(date_to+timedelta(days=DAY_TO)).strftime("%Y-%m-%d")
        return  date_to

    _defaults={
        'schedule_id': _get_schedule_id,
        'date_from': _get_date_from,
        'date_to': _get_date_to,
        'mon': True,
        'tue': True,
        'wed': True,
        'thu': True,
        'fri': True,
        'sat': True,
        'sun': True,
    }

    def copy2schedule(self,ids,context={}):
        obj=self.browse(ids)[0]
        if not obj.schedule_id:
            raise Exception("Please save schedule before copy")

        schedule=get_model("clinic.schedule").browse(obj.schedule_id.id)
        lines=[]
        for line in schedule.lines:
            lines.append(('create',{
                'nurse_id': line.nurse_id.id,
                'cycle_id': line.cycle_id.id,
            }))
        days=[
            obj.mon and 1 or 0,
            obj.tue and 2 or 0,
            obj.wed and 3 or 0,
            obj.thu and 4 or 0,
            obj.fri and 5 or 0,
            obj.sat and 6 or 0,
            obj.sun and 7 or 0,
            ]
        days=[day for day in days if day]
        ntoday=1
        date_from=datetime.strptime(obj.date_from,FMT_DATE)
        date_to=datetime.strptime(obj.date_to,FMT_DATE)
        day_total=(date_to-date_from).days+ntoday
        schedules=[]
        schedule_date=obj.schedule_id.date
        time_start=obj.schedule_id.time_start[11:]
        time_stop=obj.schedule_id.time_stop[11:]
        exist_date={}
        dom=[]
        dom.append(['date','>=',obj.date_from])
        dom.append(['date','<=',(date_to+timedelta(days=8)).strftime(FMT_DATE)])
        branch=schedule.branch_id
        department=schedule.department_id
        if branch:
            dom.append(['branch_id','=',branch.id])
        if department:
            dom.append(['department_id','=',department.id])
        for r in get_model("clinic.schedule").search_read(dom,['date','state']):
            exist_date.update({
                r['date']:{
                    'id': r['id'],
                    'date': r['date'],
                    'state': r['state'],
                    'branch_id': branch.id,
                    'department_id': department.id,
                }})

        for weekday in days:
            wd=date_from.weekday() 
            start_date=date_from
            while wd != weekday-1:
                start_date+=timedelta(days=1)
                wd=start_date.weekday()
            #XXX should gen only in scope
            if start_date.strftime(FMT_DATE) > date_to.strftime(FMT_DATE):
                continue
            count=0
            tmp=start_date
            while count < day_total:
                tmp=start_date+timedelta(days=count)
                date=tmp.strftime(FMT_DATE)
                exist_vals=exist_date.get(date,{})
                if exist_vals:
                    eid=exist_vals['id']
                    edate=exist_vals['date']
                    estate=exist_vals['state']
                    if edate==date and estate=='draft':
                        get_model("clinic.schedule").delete([eid])
                        print("delete ", exist_date)
                count+=7 # looking for next week if dow is not exist
                if date not in [v['date'] for k,v in exist_date.items()]+[schedule_date]:
                    schedules.append({
                        'date': date,
                        'branch_id': branch.id,
                        'department_id': department.id,
                        'lines': lines,
                    })
                else:
                    print("copy to exist nurse ", lines)
                    dom2=[['date','=',date]]
                    if branch:
                        dom2.append(['branch_id','=',branch.id])
                    if department:
                        dom2.append(['department_id','=',department.id])
                    schds=get_model("clinic.schedule").search_browse(dom2)
                    if schds and lines:
                        schd=schds[0]
                        for line in schd.lines:
                            line.delete()
                        schd.write({'lines': lines})
                    
            start_date=tmp

        for sc in schedules:
            date=sc['date']
            sc['time_start']='%s %s'%(date,time_start)
            sc['time_stop']='%s %s'%(date,time_stop)
            sc_id=get_model("clinic.schedule").create(sc)
            print('create', sc['date'])

        return {
            'next': {
                'name': 'clinic_schedule',
                'mode': 'list',
                #'active_id': obj.schedule_id.id,
            },
            'flash': 'Copy successully',
        }

ScheduleCopy.register()