class WorkLog {

    #content = h.div('content modal form')

    createWorkLogForm(){
        let time = h.input("integer");
        let cbTimeUnit = dom.select("worklog")
            .add(dom.option({'label' : 'global.unit.hour', 'value' : 'h'}))
            .add(dom.option({'label' : 'global.unit.day', 'value' : 'd'}))
            .add(dom.option({'label' : 'global.unit.minute', 'value' : 'm'}));

    }
}



class MagicWorkTime{

    #issueId
    #window
    #resultarea
    static MINUTES_IN_WEEK = 2400;
    static MINUTES_IN_DAY = 480;
    static MINUTES_IN_HOUR = 60;
    static MINUTES = 1;
    static HR = 'hr'
    static ISSUE = 'issue'
    #possibleHourWord = ['h','hour', 'hours']
    #possibleWeekWord = ['w', 'week', 'weeks']
    #possibleDayWord = ['d', 'day', 'days']
    #possibleMinutWord = ['m', 'min', 'minutes']
    #curentDate = MagicDateChooser.getToday()
    #groupId;
    #projectId
    hours = []
    weeks = []
    days = []
    minutes = []
    totalHour = 0
    #hiddenElemIssue = h.input("hidden")
    #hiddenElemHr = h.input("hidden").text(cache.get("___user_key"),false)

    constructor(issueId, groupId, projectId = null){
        this.#hiddenElemIssue.text(issueId, false)
        this.#groupId = groupId;
        if(_.notNull(projectId)){
            this.#projectId = projectId;
        }
        this.build()
    }


    dateListner = (event)=>{     
        if(_.e(DateEvent.DATE_SELECTED, event.eventName )){
             this.#curentDate = event.data;
        }    
    }

    build(){
        let _this = this
        this.#window = dom.createModal(dom.REMOVE_TYPE_REMOVE)
        .cl('work_time_window')
            .add(dom.createCloseImage()
                .click(function () {
                    _this.close();
                })
                )
            .add(h.div('work_time_input_div')
                .add(h.div('work_time_title').text('global.work.log'))
                .add(h.div('input_time_title').text("global.time.spent"))
                .add(h.input('text')
                    .placeHolder('2weeks 5days 1.5hour',  false)
                    .inputFunc((e)=>_this.dellCommaSpaces(e.value))
                    .focus()
                    )
                .add(h.div('input_time_title').text("global.an.estimate.of.how.much.time.you.have.spent.working")))
            .appendToBody();

        this.description = h.textArea();
        h.div('description_div')
            .add(h.div("description_title").text('global.description'))
            .add(this.description) 
            .appendTo(this.#window);  

        let calendar = h.div('work_log_calendar').text(MagicDateChooser.getToday(), false)
        h.div('celendar_div')
            .add(h.div('celendar_title').text('global.select.the.date.you.worked.until'))
            .add(calendar)
            .appendTo(this.#window);
        let hr = h.div('chooser_class');   
        h.div('hr_worklog').text('global.worklog.for.hr')
            .add(hr)
            .appendTo(this.#window)
        this.createChooser(hr, MagicWorkTime.HR, this.#hiddenElemHr)   
        
        let issue = h.div('chooser_class');
        h.div('issue_worklog').text('global.worklog.for.issue')
            .add(issue)
            .appendTo(this.#window)

        this.createChooser(issue, MagicWorkTime.ISSUE, this.#hiddenElemIssue) 
        this.options = new DateOptions(calendar, ".", "dd.mm.yyyy", '', this.dateListner);
        this.chooser =  new MagicDateChooser(this.options).init();
        this.#resultarea = h.input('text').readOnly().cl('bgc_white').appendTo(this.#window);
        h.input("button").text('global.cancel').click(()=>{this.close()}).appendTo(this.#window);
        this.sendBtn = h.input('button').text('global.save').click(()=>{this.send()}).appendTo(this.#window);
        
    }

    createChooser(where, what, hiddenEl){
        if (_e(hiddenEl.val(), 0)){return  undefined}
        let path = Environment.dataApi + "/api/v2/flaw/" + what + "/root/fetch/details/" + hiddenEl.val()
        Executor.runGet(path, (data)=>{
            let dataForChooser = this.changeObjForChooser(data.data)
            new MagicRemoteChooser(
                where,
                dataForChooser,
                hiddenEl,
                "",
                this.createHeader(what),
              );
        })
    }

    changeObjForChooser(data) {
        let newData = {
          key: data.id,
          value: data.name,
          additional: {
            icon: null,
          },
        };
        if (_.notNull(data)) {
          newData.key = data.id;
          newData.value = data.name;
          newData.additional.icon = data.icon;

        } 

        return newData;
      }

    createHeader(field) {
        return {
            getData() {
                return {
                    searchName: field,
                    searchField: "name"
                }
            },
            getField() {
                return field;
            },
            getType() {
                return 'object_chooser'
            }
        };
    }

    close(){
        this.#window.hideModal()
    }

    dellCommaSpaces(input){  
        let str = input.replace(/ +/g, ' ').trim();
        let array = str.split(',').join('.').split(' ')
        this.splitInputs(array)
    }

    splitInputs(array){
        this.clearValues();
        array.forEach((e) => {
            e.includes('h') && this.hours.push(e)
            e.includes('w') && this.weeks.push(e)
            e.includes('d') && this.days.push(e)
            e.includes('m') && this.minutes.push(e)
        })

        this.combineHour()
    }

    clearValues(){
        this.hours = []
        this.weeks = []
        this.days = []
        this.minutes = []
        this.totalHour = 0
        this.#resultarea.text('', false)
    }

    combineHour(){
        this.minutes.forEach((e)=> this.totalHour += parseFloat(e))
        this.hours.forEach((e)=> this.totalHour += parseFloat(e)* MagicWorkTime.MINUTES_IN_HOUR)
        this.days.forEach((e)=> this.totalHour += parseFloat(e) * MagicWorkTime.MINUTES_IN_DAY)
        this.weeks.forEach((e)=> this.totalHour += parseFloat(e) * MagicWorkTime.MINUTES_IN_WEEK)
        this.prevShowTime()
    }

    prevShowTime(){
            let week
            let days
            let hour
            let min
            let time = this.totalHour
    
            if(time >= MagicWorkTime.MINUTES_IN_DAY){
                days = Math.floor(time/MagicWorkTime.MINUTES_IN_DAY)
                time = time - MagicWorkTime.MINUTES_IN_DAY*days
            }
    
            if(time >= MagicWorkTime.MINUTES_IN_HOUR){
                hour = Math.floor(time/MagicWorkTime.MINUTES_IN_HOUR)
                time = time - MagicWorkTime.MINUTES_IN_HOUR*hour
            }
    
            if(time >= MagicWorkTime.MINUTES){
                min = time
            }
    
            let myTime = ''
            days ? myTime += days + ' day ' : null
            hour ? myTime += hour + ' hour ' : null
            min ? myTime += min + ' min' : null
    
            this.#resultarea.text(myTime, false)
            return myTime
      
    }

    send(){

        let _this = this;
        let payload = {
            amount: this.totalHour,
            issue : parseInt(this.#hiddenElemIssue.val()),
            date : this.#curentDate,
            group : parseInt(this.#groupId),
            description: this.description.val(),
            project: parseInt(this.#projectId),
            hr: parseInt(this.#hiddenElemHr.val()),
        }

        if(this.totalHour > 0){ 
            Executor.runPostWithPayload(Environment.dataApi + '/api/v2/flaw/work_log/add' , function (data) {
                _this.close();
                dom.successMessage();
            }, payload)
        }else{
            this.#resultarea.text( 'global.enter.correct.value' )  
        }
    }

}