package elements;


import elements.exceptions.ReadErrorChatException;
import elements.exceptions.ReadErrorListException;

import java.time.LocalDate;
import java.util.*;

/**
 * Created by Guillermo Serrahima on 4/21/16.
 */
public class Chat {
    private static final String NAME_TAG = "Name=";
    private static final String ID_TAG = "ChatID=";
    private static final String BETA_TAG = "BetaEnabled=";

    private String name;
    private Long chatId;
    private Map<String, ArrayList<ChatListItem>> lists;
    private boolean beta;

    private Chat() {
        lists = new HashMap<String, ArrayList<ChatListItem>>();
        name = null;
        chatId = null;
        beta = false;
    }

    public Chat(String n, long chat_id) {
        this();
        name = n;
        chatId = chat_id;
    }

    public Chat(List<String> lines) throws ReadErrorChatException {
        this();
        loadInfo(lines);
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Long getChatId() {
        return chatId;
    }

    public boolean exists(String list) {
        return lists.containsKey(list);
    }

    public void add(String listName, ArrayList<ChatListItem> list) {
        lists.put(listName, list);
    }

    public void add(String list) {
        lists.put(list, new ArrayList<ChatListItem>());
    }

    public void addItem(String item, int value, String list) {
        lists.get(list).add(new ChatListItem(item, value));
    }

    public String printList(String list) {
        ArrayList<ChatListItem> l = lists.get(list);
        String s = list + ":\n\n";

        for(int i = 0; i < l.size(); i++) {
            s += l.get(i) + "\n";
        }

        return s.trim();
    }

    public String orderAlphabetically(String list) {
        ArrayList<ChatListItem> toOrder = lists.get(list);

        toOrder.sort(new ChatListItemComparator());

        return "Lista ordenada.\n" + printList(list);
    }

    public ArrayList<List<String>> saveLists() {
        ArrayList<List<String>> listDocs = new ArrayList<List<String>>();
        List<String> lines;

        Iterator it = lists.entrySet().iterator();

        while(it.hasNext()) {
            lines = new ArrayList<String>();

            Map.Entry<String, ArrayList<ChatListItem>> entry = (Map.Entry<String, ArrayList<ChatListItem>>) it.next();
            lines.add(entry.getKey());

            if(name != null) {
                lines.add("#Chat name: " + name);
            }
            lines.add("#List name: " + entry.getKey());

            ArrayList<ChatListItem> list = entry.getValue();

            for(int i = 0; i < list.size(); i++) {
                lines.add(list.get(i).saveItem());
            }

            listDocs.add(lines);
        }

        return listDocs;
    }

    public void loadList(String listName, List<String> lines) throws ReadErrorListException {
        ArrayList<ChatListItem> list = new ArrayList<ChatListItem>();

        for(int i = 0; i < lines.size(); i++) {
            //Comprueba si la línea es un comentario.
            if(lines.get(i).startsWith("#") || lines.get(i).length() < 1) {
                //do nothing
            }
            //Comprueba si la línea es un comentario. (Caso: comentario precedido de cabecera UTF-8 en Windows)
            else if(lines.get(i).startsWith("\uFEFF#")) {
                //do nothing
            }
            else {
                System.out.println("Reading " + lines.get(i));
                String[] reading = lines.get(i).split(";");
                list.add(new ChatListItem(reading[0], Integer.parseInt(reading[1])));
            }
        }
    }

    public List<String> saveInfo() {
        ArrayList<String> lines = new ArrayList<String>();

        if(name != null) lines.add(NAME_TAG + name);

        if(chatId != null) lines.add(ID_TAG + chatId);

        if(beta == true) lines.add(BETA_TAG + "yes");
        else lines.add(BETA_TAG + "no");

        return lines;
    }

    private void loadInfo(List<String> lines) throws ReadErrorChatException {
        String line;

        for(int i = 0; i < lines.size(); i++) {
            line = lines.get(i);

            if(line.startsWith("#") || line.length() < 1) {
                //do nothing
            }
            //Comprueba si la línea es un comentario. (Caso: comentario precedido de cabecera UTF-8 en Windows)
            else if(line.startsWith("\uFEFF#")) {
                //do nothing
            }
            else if(line.startsWith(NAME_TAG)) {
                if(name != null) throw new ReadErrorChatException("There was more than one name.");
                name = line.substring(NAME_TAG.length());
            }
            else if(line.startsWith(BETA_TAG)) {
                line = line.substring(BETA_TAG.length());
                if(line.equals("yes")) beta = true;
                else beta = false;
            }
            else if(line.startsWith(ID_TAG)) {
                line = line.substring(ID_TAG.length());
                try {
                    chatId = Long.parseLong(line);
                } catch(Exception e) {
                    throw new ReadErrorChatException("The chat id couldn't be read.");
                }
            }
            else {
                throw new ReadErrorChatException("There was an unrecognizable line in the chat info file.");
            }
        }
    }
}

class ChatListItemComparator implements Comparator<ChatListItem> {

    @Override
    public int compare(ChatListItem entr1, ChatListItem entr2) {
        return entr1.compareTo(entr2);
    }
}
