# -*- coding: utf-8 -*-
from __future__ import print_function
# from importlib import reload
from datetime import timedelta
import time
import emmcsl4a

__author__ = 'jaehyek.choi'

"""
purpose :

"""

"""
from __future__ import division
"""

from multiprocessing import Process
from threading import Thread, Event

import pickle

import sys
import os
import emmcfunc
import emmctest


def pretask(clsvar, msg_client) :

    emmcsl4a.disableAirplaneMode(False)

    msg_client.SendMsg ("main before tasksleep" )


    ## ______________ gather the device info, and make the marker on device   __________________
    emmcfunc.gatherEmmcDeviceInfo(clsvar )

    listskipblockname = [ "persist", "mpt", "system", "cache", "userdata"]
    clsvar.crcstartblockaddr = 0
    clsvar.crc0filladdress = True
    if clsvar.modelname == "LG-H440n" :
        clsvar.crcstartblockaddr = clsvar.userdata[0]


    result = emmcfunc.skipCheckingBlock(clsvar, msg_client, listskipblockname)
    if result == False :
        msg_client.SendMsg("failed of skipCheckingBlock")
        exit()



    ## ______________ prepare the Partition with Mark .   __________________
    msg_client.SendMsg ("main before BuildCRC32Table" )

    result = emmcfunc.BuildCRC32Table(clsvar, msg_client)
    if result == False :
        msg_client.SendMsg("failed of BuildCRC32Table")
        exit()

    ## ______________ save the clsvar .   __________________
    # with open('clsvar.pickle', 'wb') as handle:
    #     pickle.dump(clsvar, handle)
    #     msg_client.SendMsg("saved the clsvar.pickle")



    ## ______________ verify the Partition with the previous mark .   __________________
    emmcfunc.setFakeEmmcWrite(clsvar, msg_client, True)

    # msg_client.SendMsg ("main before RebuildCRC32Table" )
    # result = emmcfunc.RebuildCRC32Table(clsvar, msg_client)
    # if result == False :
    #     msg_client.SendMsg("failed of RebuildCRC32Table")
    #     exit()


    ## ______________ print the partition summary .   __________________
    # emmcfunc.printpartitioninfo(clsvar, msg_client)


def posttask(clsvar, msg_client) :

    ## just after taskop =0 , we save the clsvar to storage.
    # emmcfunc.restoreUserdataWithZero(clsvar, msg_client)

    emmcfunc.setFakeEmmcWrite(clsvar, msg_client, False)


    # with open('clsvar.pickle', 'wb') as handle:
    #     pickle.dump(clsvar, handle)

    msg_client.SendMsg("Main process is terminated...")


def main():
    os.chdir("/sdcard/com.hipipal.qpyplus/scripts3")

    ## ______________ initialize the variables class   __________________
    # if os.path.exists("clsvar.pickle") :
    #     with open('clsvar.pickle', 'rb') as handle:
    #         clsvar = pickle.load(handle)
    # else :
    #     clsvar = emmcfunc.clsVariables()

    clsvar = emmcfunc.clsVariables()
    ## ______________ setup of test parameters   __________________
    clsvar.pathmmc = emmcfunc.getEmmcPath(clsvar)
    clsvar.EmmcGBSize = emmcfunc.getEmmcGBSize(clsvar)
    clsvar.modelname = emmcfunc.getModelName(clsvar)
    clsvar.DeviceSerialNo = emmcfunc.getDeviceSerialNo(clsvar)
    clsvar.EmmcFirmwareVersion = emmcfunc.getEmmcFirmwareVersion(clsvar)
    clsvar.addrSPMIEMMCVDD = emmcfunc.getAddrSPMIEMMCVDD(clsvar)

    clsvar.intervalrebuild = 10000
    clsvar.currcountrebuild = 0
    # clsvar.setupMarkforUserdata = "crc32"  # "addrfillpartial", "addrfillfull"
    # if clsvar.EmmcGBSize <= 4 :
    #     clsvar.incMark = 8192  ## 4MB
    # elif clsvar.EmmcGBSize <= 8 :
    #     clsvar.incMark = 16384  ## 8MB
    # elif clsvar.EmmcGBSize <= 16 :
    #     clsvar.incMark = 16384 * 2   ## 16MB
    # else :
    #     clsvar.incMark = 16384 * 4   ## 32MB

    clsvar.incMark = 8192
    clsvar.taskname = "sleep"



    # clsvar.modelname = "testmodel"
    # clsvar.DeviceSerialNo = "testNo"

    ## ______________ initialize the msg client class   __________________
    SERVERIP = '172.21.26.41'
    # SERVERIP = '192.168.219.142'
    # SERVERIP = '10.163.58.69'

    msg_client = emmctest.clsMsgClent( "%s_%s_%s"%(clsvar.DeviceSerialNo ,clsvar.EmmcGBSize, clsvar.taskname) ,clsvar.modelname,SERVERIP )
    # msg_client.onlylocal = True
    msg_client.SendMsg ("starting msg_client")

    msg_client.SendMsg("EmmcFirmwareVersion,%s"% clsvar.EmmcFirmwareVersion )
    msg_client.SendMsg ("curr dir,%s" % os.path.realpath("."))

    msg_client.SendMsg ("modelname,%s" % clsvar.modelname)
    msg_client.SendMsg ("pathmmc,%s" % clsvar.pathmmc)
    msg_client.SendMsg ("EmmcGBSize,%s" % clsvar.EmmcGBSize)
    msg_client.SendMsg ("addrSPMIEMMCVDD,%s" % clsvar.addrSPMIEMMCVDD)
    msg_client.SendMsg ("taskname,%s" % clsvar.taskname)
    msg_client.SendMsg ("clsvar.incMark,%s"%(clsvar.incMark) )


    ## ______________ launch the wake-up process   __________________
    runnerKey = Process( target=emmctest.taskGenKeyEvent, args=(clsvar,msg_client,))
    runnerKey.start()


    main_sec_start = int(round(time.time()))

    try:
        pretask(clsvar, msg_client)

        if clsvar.taskname == "sleep" :
            runnertask = Process( target=emmctest.scenario_SleepWake, args=(clsvar, msg_client,))
            runnertask.start()

        elif clsvar.taskname == "ref" :
            runnertask = Process( target=emmctest.scenario_referring, args=(clsvar, msg_client,))
            runnertask.start()

        # else:
        #     runnertask = Process( target=emmctest.scenario_VDDShaking, args =(clsvar, msg_client,))
        #     runnertask.start()

        while(True):
            time.sleep(60)
            # if runnerKey.is_alive() == False :
            #     runnerKey.terminate()
            #     runnerKey = 0
            #     runnerKey = Process( target=emmctest.taskGenKeyEvent, args=(clsvar,msg_client,))
            #     runnerKey.start()

            if runnertask.is_alive() == False :
                break

        posttask(clsvar, msg_client)

    except Exception as e:
        import traceback
        msgerr = traceback.format_exc()
        msgerr = msgerr.replace("\n", "$")

        ## replace the "\n" with "$"
        msg_client.SendMsg("____Error : main ____")
        msg_client.SendMsg(msgerr)
        msg_client.SendMsg("finishing  main function" )



    sec_diff = int(round(time.time())) - main_sec_start
    msg_client.SendMsg("__ main loop collapsed time,%s"%(timedelta(seconds = sec_diff)))
    emmcfunc.setFakeEmmcWrite(clsvar, msg_client, False)

    runnerKey.terminate()

if __name__ == "__main__":
    main()