import {global} from "http://talk.kospo.co.kr:3000/static/js/module/variable.js";
import {HubEvent} from "http://talk.kospo.co.kr:3000/static/js/module/hubEvent.js";
import Common from "http://talk.kospo.co.kr:3000/static/js/utils.js";
import {talkEvent} from "http://talk.kospo.co.kr:3000/static/js/module/talkEvent.js";
import {getMessageAll, getTalkList, getMoreMessageAll} from "http://talk.kospo.co.kr:3000/static/js/module/apis.js";
import receiver from "http://talk.kospo.co.kr:3000/static/js/module/receiver.js";

export default class Hub {
    constructor() {
        this.controller = new AbortController();
        this.signal = this.controller.signal;
    }


    install() {
        return new Promise(async (resolve, reject) => {
            if ('serviceWorker' in navigator) {
                navigator.serviceWorker.register(global.option.serviceWorkerLocation, {updateViaCache: 'none'})
                    .then(async registration => {
                        global.registration = registration;
                        let checker = true;
                        while (checker) {
                            if (global.registration.active !== undefined && global.registration.active !== null) checker = false;
                            await Common.sleep(5)
                        }
                        // 서비스워커 업데이트
                        registration.update();

                        // 서비스 워커 설치 완료후 HUB 소켓 연결 명령
                        HubEvent.connect({
                            type: 'CONNECT',
                            tabId: global.tabId,
                            url: global.apiUrl,
                            sabun: global.user.sabun,
                            encSabun: global.option.encSabun,
                            site: global.currentUrl
                        })

                        resolve();
                    })
                    .catch(error => {
                        console.error('Service Worker registration failed:', error);
                        reject();
                    });
            }
        })
    }

    // HUB 소켓 리시버 정의
    start() {
        console.log('hub message event start', new Date())
        // navigator.serviceWorker.removeEventListener('message', this.message, {signal: this.controller.signal})
        navigator.serviceWorker.addEventListener('message', this.message,{signal: this.signal})
    }

    stop() {
        console.log('hub message event stop', new Date())
        this.controller.abort();
        this.controller = new AbortController();
        this.signal = this.controller.signal;
    }

    message(event) {

        const payload = event.data;

        if(payload.type === 'PING') {
            // console.log('PING', new Date())
            try {
                global.registration.active.postMessage({
                    type: 'PONG'
                });
            } catch(e) {}
        } else if (payload.type === 'GETUP') {
            global.serviceWorkerConnect = true;
        } else if (payload.type === 'HUB_RECONNECT') {
            HubEvent.close({
                type: 'TAB_CLOSE',
                tabId: global.tabId,
                url: global.apiUrl,
                sabun: global.user.sabun,
                channelSabun: global.user.sabun,
                site: global.currentUrl
            })
            global.hub.install().then(() => {
                // global.hub.start();
                HubEvent.start(global.talkParams({
                    type: 'START',
                    tabId: global.tabId
                }))
                // getMessageAll(false)
                getMoreMessageAll()

                global.registration.active.postMessage({'type': 'HUB_RECONNECT_SUCCESS'})
            });
        } else if (payload.type === 'SEND_OTHER_INIT') {
            if (Common.isMaster()) {
                HubEvent.otherInit({
                    type: 'OTHER_INIT',
                    talkData: global.talkData,
                    insSabun: global.user.sabun,
                    tabId: global.tabId
                })
            }
        } else if (payload.type === 'SEND_SET_MASTER') {
            if (!Common.isMaster()) {
                global.init = false;
                talkEvent.reConnect()
            }
        } else if (payload.type === 'SEND_TYPED') {
            if (Common.isMaster()) {
                payload.type = payload.type.replace('SEND_', '')
                talkEvent.send(payload)
            }
        } else if (payload.type === 'OTHER_INIT') {
            if (!Common.isMaster()) {
                receiver.otherInit(payload)
            }
        } else if (payload.type === 'SEND') {
            if (Common.isMaster()) {
                talkEvent.send(payload)
            }
        } else if (payload.type === 'JOIN') {
            receiver.join(payload)
        } else if (payload.type === 'CHANGE') {
            receiver.change(payload)
        } else if (payload.type === 'START') {
            receiver.start(payload)
        } else if (payload.type === 'LEAVE') {
            receiver.leave(payload)
        } else if (payload.type === 'DELETE') {
            receiver.delete(payload)
        } else if (payload.type === 'WORK_ONLINE') {
            receiver.workOnline(payload)
        } else if (payload.type === 'WORK_OFFLINE') {
            receiver.workOffline(payload)
        } else if (payload.type === 'ONLINE') {
            receiver.online(payload)
        } else if (payload.type === 'OFFLINE') {
            receiver.offline(payload)
        } else if (payload.type === 'ERROR') {
            receiver.error(payload)
        } else if (payload.type === 'STATUS') {
            receiver.message(payload)
        } else if(payload.type === 'EXTERNAL_SAVE') {
            receiver.externalSave(payload)
        } else if (payload.type === 'INTRO') {
            receiver.intro(payload)
        } else if (payload.type === 'MESSAGE') {
            global.checker.flag = false;
            global.checker.inDate = '';
            receiver.message(payload);
            const chatContent = global.shadowRoot.querySelector('#chat-content');
            const content = chatContent.querySelector('.simplebar-content');
            const typedProgress = content.querySelector('.your-dot-progress');
            if(typedProgress) {
                const clone = typedProgress.cloneNode(true)
                talkEvent.messageUnTyped()
                content.insertAdjacentElement('beforeend', clone)
            }
        } else if(payload.type === 'QUESTION') {
            receiver.message(payload);
        } else if (payload.type === 'INFO_MESSAGE') {
            receiver.infoMessage(payload)
        } else if (payload.type === 'CLOSE') {
            receiver.close(payload);
        } else if (payload.type === 'TYPED') {
            console.log('service worker message', payload)
            receiver.typed(payload);
        } else if (payload.type === 'UNTYPED') {
            console.log('service worker message', payload)
            receiver.untyped(payload);
        } else if (payload.type === 'READ') {
            receiver.read(payload);
        } else if (payload.type === 'ATTACH_INIT') {
            receiver.attachStart(payload);
        } else if (payload.type === 'ATTACH_PROGRESS') {
            receiver.attachProgress(payload);
        } else if (payload.type === 'ATTACH_END') {
            receiver.attachEnd(payload);
        } else if (payload.type === 'MORE_MESSAGE_LINE') {
            if (payload.tabId !== global.tabId) {
                receiver.moreMessageLine(payload)
            }
        } else if (payload.type === 'DELETE') {
            /*삭제처리*/
            if (localStorage.getItem('talkId') === payload.talkId) {
                const chatBack = global.shadowRoot.querySelector('.contacts-list-show');
                chatBack.click();
            }
            talkEvent.talkRemove(payload.talkId)
        } else if (payload.type === 'MARK') {
            /*보관처리*/
            talkEvent.talkMark(payload.talkId)
        } else if (payload.type === 'UNSUBSCRIBE') {
            /*새로운 탭 활성화시 현재 탭 외 모든 구독 해제 조건(탭아이디가 동일 하지 않으며 모든 로딩이 완료)*/
            if (payload.tabId !== global.tabId && global.init) {
                talkEvent.allUnsubscribe();
            }
        } else if (payload.type === 'WORK_COUNT') {
            /*현재 업무 카운트*/
            receiver.changeLoginInfo(payload)
        } else if(payload.type === 'SW_RECONNECT') {
            console.log('sw_reconnect')
            // 개인 사번 소켓 연결
            try{global.subscribeList[global.user.sabun] = talkEvent.userSubscribe();}catch(e){}
            // 업무별 소켓 연결
            try{global.subscribeList[global.work.workId] = talkEvent.workSubscribe();}catch(e){}
            // 톡방 재갱신
            // getMessageAll(false)
            getMoreMessageAll()
            if (Common.isMaster()) {
                // 허브설정
                HubEvent.start(global.talkParams({
                    type: 'START',
                    tabId: global.tabId
                }))

                // 현재 탭 외 모든 탭 구독 해지
                HubEvent.send(global.talkParams({
                    type: 'UNSUBSCRIBE',
                    tabId: global.tabId
                }))
            }
        } else if(payload.type === 'HEARTBEAT') {
            console.log("PONG")
        }
    }
}