package edu.fiu;

import edu.fiu.models.User;
import edu.fiu.repositories.ActivityRepository;
import edu.fiu.repositories.UserRepository;
import org.jdbi.v3.core.Handle;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

/**
 *
 * Class to init DB with tables and Data
 */

public class DbInitializer
{
    /**
     * Create necessary tables in the database
     * Will need to check if this is required when using persistant strg
     * @param h
     */
    public static void Initialize(Handle h){
        //Create users table
        h.createUpdate("create table if not exists users " +
                "(id integer primary key, " +
                "name varchar(255) not null, " +
                "hash varchar(255) not null, " +
                "active bit not null default 0, " +
                "host varchar(255) null " +
                ")")
                .execute();

        //Create Activity table
        h.createUpdate("create table if not exists activities " +
                "(id integer primary key, " +
                "name varchar(255) not null, " +
                "type varchar(255), " +
                "dataPath varchar(255), " +
                "status varchar(255) " +
                ")")
                .execute();

        //Create Activity Progress table
        h.createUpdate("create table if not exists progress " +
                "(state varchar(10) not null, " +
                "userId integer not null, " +
                "activityId integer not null, " +
                "content varchar(255), " +
                "date long" +
                ")")
                .execute();

        //Create session table
        h.createUpdate("create table if not exists sessions" +
                "(id integer primary key, " +
                "token varchar(36) not null, " +
                "userIds nvarchar(255) not null, " + //How the frick to store a list of ints in sql? String it is
                "active bit not null default 1, " +
                "dateTime varchar(255) not null" +
                ")")
                .execute();
        
        //Create UserStory table
        h.createUpdate("create table if not exists userStory" +
                "(userID integer not null, " +
                "text text not null, " +
                "submitTime text not null " +
                ")")
                .execute();  

    }

    /**
     * Seeds the database with initial data
     * Will need to check if this needs to be done if we have persistant strg
     * @param h
     */
    public static void Seed(Handle h){

        UserRepository repo = h.attach(UserRepository.class);
        //ActivityRepository r = h.attach(ActivityRepository.class);
        //SessionRepository sessions = h.attach(SessionRepository.class);
        ActivityRepository activityRepo = h.attach(ActivityRepository.class);
        
        if(repo.get("admin") == null) {
            repo.create(new User(0, "admin", "foo", 0, ""));
            //sessions.create("123123", "0", true, "");
        
        }
        System.out.printf("***ADMIN INFO: %s ***\n", repo.get("admin"));
        //System.out.printf("***SESSION: %s ***\n", sessions.get("123123"));

        if ( activityRepo.list().isEmpty() ){

            JSONParser jsonParser = new JSONParser();

            try ( FileReader reader = new FileReader("./public/api/activities.json") )
            {

                Object obj = jsonParser.parse(reader);
                JSONArray activityList = (JSONArray) obj;

                for(Object o: activityList){
                if ( o instanceof JSONObject ) {

                    JSONObject activity = (JSONObject) o;
                        
                    Long id = (Long) activity.get("id");
                    String name = (String) activity.get("name");
                    String type = (String) activity.get("type");
                    String datapath = "empty";
                    String status = "enabled";  
                    activityRepo.create2(id.intValue(), name, type, datapath, status);
                }

                reader.close();
            }
 
            } catch (FileNotFoundException e) {
            e.printStackTrace();
            } catch (IOException e) {
            e.printStackTrace();
            } catch (ParseException e) {
            e.printStackTrace();
            }       

        }
    }
}
