import { _decorator, Component, Node, game } from 'cc';
import { UserGameData, UserLevelData } from './DataModel';
import { Cards_Constants } from '../../constants/Cards_Constants';
const { ccclass } = _decorator;

@ccclass('SaveManager')
export class SaveManager extends Component
{
    public m_DebugResetFlag: boolean = false;
    public m_HasResetData: boolean = false;

    private userGameData: UserGameData;

    public fn_SetIsFirstTimeUser()  
    {
        if (localStorage.getItem(Cards_Constants.FIRST_SESSION_CONST) == null)
            localStorage.setItem(Cards_Constants.FIRST_SESSION_CONST, Cards_Constants.TRUE);
        else if (localStorage.getItem(Cards_Constants.FIRST_SESSION_CONST) == Cards_Constants.TRUE)
            localStorage.setItem(Cards_Constants.FIRST_SESSION_CONST, Cards_Constants.FALSE);
    }

    public fn_IsFirstTimeUser() : boolean 
    {
        console.log("localStorage.getItem(Cards_Constants.FIRST_SESSION_CONST): " + localStorage.getItem(Cards_Constants.FIRST_SESSION_CONST));
        return localStorage.getItem(Cards_Constants.FIRST_SESSION_CONST) == null || localStorage.getItem(Cards_Constants.FIRST_SESSION_CONST) == Cards_Constants.TRUE;
    }

    public fn_SetGameData(userData: UserGameData) : void
    {
        this.userGameData = userData;
        this.fn_SaveGameData();
    }

    public fn_LoadUserData() : UserGameData
    {
        let gameDataStr = localStorage.getItem(Cards_Constants.GAME_DATA_CONST);
        if (gameDataStr != null)
        {
            this.userGameData = JSON.parse(gameDataStr);
            return this.userGameData;
        }

        return null;
    }

    public fn_SaveGameData() : void
    {
        if (this.m_HasResetData || this.m_DebugResetFlag)
        {
            return;
        }

        if (this.userGameData)
        {
            localStorage.setItem(Cards_Constants.GAME_DATA_CONST, JSON.stringify(this.userGameData));
        }
    }

    public fn_ResetData() : void 
    {
        localStorage.clear();
        this.m_HasResetData = true;
    }
}

