package com.luticate.auth.dbo;

import com.luticate.utils.dbo.LuDbo;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.List;
import java.util.Vector;

/**
 * Created by robin on 11/27/15.
 */
public class LuFullLoginDbo extends LuDbo {

    private LuLoginDbo _loginDbo;

    private List<LuPermissionDbo> _permissions;

    public LuLoginDbo getLoginDbo() {
        return _loginDbo;
    }

    public void setLoginDbo(LuLoginDbo loginDbo) {
        _loginDbo = loginDbo;
    }

    public List<LuPermissionDbo> getPermissions() {
        return _permissions;
    }

    public void setPermissions(List<LuPermissionDbo> permissions) {
        _permissions = permissions;
    }

    @Override
    public void fromJson(JSONObject json) throws JSONException {
        _loginDbo = new LuLoginDbo();
        _loginDbo.fromJson(json.getJSONObject("LoginDbo"));

        _permissions = new Vector<>();
        JSONArray array = json.getJSONArray("Permissions");
        for (int i = 0; i < array.length(); ++i) {
            LuPermissionDbo perm = new LuPermissionDbo();
            perm.fromJson(array.getJSONObject(i));
            _permissions.add(perm);
        }
    }

    @Override
    public HashMap<String, Object> toArray() {
        HashMap<String, Object> array = new HashMap<>();
        array.put("LoginDbo", _loginDbo.toArray());
        JSONArray permissions = new JSONArray();
        for (LuPermissionDbo perm : _permissions) {
            permissions.put(perm.toArray());
        }
        array.put("Permissions", permissions);
        return array;
    }

    public boolean hasPermission(String permission)
    {
        for (LuPermissionDbo perm : _permissions)
        {
            if (perm.getName().equals(permission))
            {
                return perm.getValue();
            }
        }
        return false;
    }
}
