import { iRememberPhonePwd } from "./types";

const KEY_REMEMBER_PWD = 'KEY_REMEMBER_PWD'

export default class LoginService {
    static instance: LoginService
    static getIntance() {
        if (!LoginService.instance) LoginService.instance = new LoginService();
        return LoginService.instance;
    }

    addPhoneWithPwdToStorage(phone: string, pwd: string) {
        const list = this.getRememberedPhonePwdList();
        const index = list.findIndex(i => i.phone === phone)
        if (index === -1) {
            list.push({
                phone,
                pwd
            })
        } else {
            list.splice(index, 1, { phone, pwd })
        }
        localStorage.setItem(KEY_REMEMBER_PWD, JSON.stringify(list))
    }

    getRememberedPhonePwdList(): iRememberPhonePwd[] {
        const value = localStorage.getItem(KEY_REMEMBER_PWD)
        const list = value && JSON.parse(value) || []
        return list;
    }

    deletePhoneInStorage(phone: string) {
        const list = this.getRememberedPhonePwdList()
        const newList = list.filter(i => i.phone !== phone)
        localStorage.setItem(KEY_REMEMBER_PWD, JSON.stringify(newList))
    }
}