import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;

import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.filechooser.FileNameExtensionFilter;

public class BusinessCardManagement {

	public final Charset CHARSET = java.nio.charset.Charset.forName("Shift_JIS");

	private Screen screen;
	private ScreenTemplates screenTemplates;
	private W4ca84254d30c423ab8e449171a5b5123 w4ca84254d30c423ab8e449171a5b5123;
	private SearchScreen searchScreen;
	private SearchCriteriaScreen searchCriteriaScreen;
	private Result result;
	private CompanyList companyList;
	private W2d109ad3739d4744a1874ac179fc38b9 w2d109ad3739d4744a1874ac179fc38b9;
	private Map<String, BusinessCardManagementElement> value = new LinkedHashMap<>();
	private Widget1 widget;
	public BusinessCardManagement(Screen screen, ScreenTemplates screenTemplates, W4ca84254d30c423ab8e449171a5b5123 w4ca84254d30c423ab8e449171a5b5123, SearchScreen searchScreen, SearchCriteriaScreen searchCriteriaScreen, Result result, CompanyList companyList, W2d109ad3739d4744a1874ac179fc38b9 w2d109ad3739d4744a1874ac179fc38b9) {
		this.screen = screen;
		this.screenTemplates = screenTemplates;
		this.w4ca84254d30c423ab8e449171a5b5123 = w4ca84254d30c423ab8e449171a5b5123;
		this.searchScreen = searchScreen;
		this.searchCriteriaScreen = searchCriteriaScreen;
		this.result = result;
		this.companyList = companyList;
		this.w2d109ad3739d4744a1874ac179fc38b9 = w2d109ad3739d4744a1874ac179fc38b9;
		load();
	}
	public Map<String, Map<String, Object>> getValue() {
		Map<String, Map<String, Object>> value = new LinkedHashMap<>();
		for (String key: this.value.keySet()) {
			BusinessCardManagementElement businessCardManagementElement = this.value.get(key);
			value.put(key, businessCardManagementElement.getValue());
		}
		return value;
	}
	public BusinessCardManagementElement getBusinessCardManagementElement(String companyName) {
		return this.value.get(companyName);
	}
	public void updateFromState(String scId, String wid, int state, String company_, String representative_, String position_, String establishment_, String address1_, String address2_, String businessdescription1_, String businessdescription2_, String companyoverview_, String URL_, String contactPerson1_, String position1_, String tel1_, String email1_, String contactPerson2_, String position2_, String tel2_, String email2_, String contactPerson3_, String position3_, String tel3_, String email3_, String contactPerson4_, String position4_, String tel4_, String email4_) {
        Map<String, BusinessCardManagementElement> temp_if15;
        if ((((state==0)&&!company_.equals(""))&&!(this.value.containsKey(company_)))) {
            this.value.put(company_,new BusinessCardManagementElement(representative_, position_, establishment_, address1_, address2_, businessdescription1_, businessdescription2_, companyoverview_, URL_, contactPerson1_, position1_, tel1_, email1_, contactPerson2_, position2_, tel2_, email2_, contactPerson3_, position3_, tel3_, email3_, contactPerson4_, position4_, tel4_, email4_));
            temp_if15 = this.value;
        } else {
            temp_if15 = this.value;
        }
        this.value = temp_if15;
		String searchCriteriaScreen = this.searchCriteriaScreen.getValue();
		String result = this.result.getValue();
		this.widget = screenTemplates.getScreenTemplate(searchCriteriaScreen).getWidgets1().getWidget1(result);
		this.widget.updateDataFromBusinessCardManagement(scId, wid, this.getValue(), searchCriteriaScreen, result);
		String w2d109ad3739d4744a1874ac179fc38b9 = this.w2d109ad3739d4744a1874ac179fc38b9.getValue();
		String companyList = this.companyList.getValue();
		this.widget = screenTemplates.getScreenTemplate(companyList).getWidgets1().getWidget1(w2d109ad3739d4744a1874ac179fc38b9);
		this.widget.updateDataFromBusinessCardManagement3(scId, wid, this.getValue(), companyList, w2d109ad3739d4744a1874ac179fc38b9);
		String w4ca84254d30c423ab8e449171a5b5123 = this.w4ca84254d30c423ab8e449171a5b5123.getValue();
		String searchScreen = this.searchScreen.getValue();
		this.widget = screenTemplates.getScreenTemplate(searchScreen).getWidgets1().getWidget1(w4ca84254d30c423ab8e449171a5b5123);
		this.widget.updateDataFromBusinessCardManagement2(scId, wid, this.getValue(), w4ca84254d30c423ab8e449171a5b5123, searchScreen);
	}
	public void updateFromState2(String scId, String wid, int state, String company_, String representative_, String position_, String establishment_, String address1_, String address2_, String businessdescription1_, String businessdescription2_, String companyoverview_, String URL_, String contactPerson1_, String position1_, String tel1_, String email1_, String contactPerson2_, String position2_, String tel2_, String email2_, String contactPerson3_, String position3_, String tel3_, String email3_, String contactPerson4_, String position4_, String tel4_, String email4_) {
        Map<String, BusinessCardManagementElement> temp_if14;
        if ((((state==0)&&!company_.equals(""))&&!(this.value.containsKey(company_)))) {
            this.value.put(company_,new BusinessCardManagementElement(representative_, position_, establishment_, address1_, address2_, businessdescription1_, businessdescription2_, companyoverview_, URL_, contactPerson1_, position1_, tel1_, email1_, contactPerson2_, position2_, tel2_, email2_, contactPerson3_, position3_, tel3_, email3_, contactPerson4_, position4_, tel4_, email4_));
            temp_if14 = this.value;
        } else {
            temp_if14 = this.value;
        }
        this.value = temp_if14;
		String searchCriteriaScreen = this.searchCriteriaScreen.getValue();
		String result = this.result.getValue();
		this.widget = screenTemplates.getScreenTemplate(searchCriteriaScreen).getWidgets1().getWidget1(result);
		this.widget.updateDataFromBusinessCardManagement(scId, wid, this.getValue(), searchCriteriaScreen, result);
		String w2d109ad3739d4744a1874ac179fc38b9 = this.w2d109ad3739d4744a1874ac179fc38b9.getValue();
		String companyList = this.companyList.getValue();
		this.widget = screenTemplates.getScreenTemplate(companyList).getWidgets1().getWidget1(w2d109ad3739d4744a1874ac179fc38b9);
		this.widget.updateDataFromBusinessCardManagement3(scId, wid, this.getValue(), companyList, w2d109ad3739d4744a1874ac179fc38b9);
		String w4ca84254d30c423ab8e449171a5b5123 = this.w4ca84254d30c423ab8e449171a5b5123.getValue();
		String searchScreen = this.searchScreen.getValue();
		this.widget = screenTemplates.getScreenTemplate(searchScreen).getWidgets1().getWidget1(w4ca84254d30c423ab8e449171a5b5123);
		this.widget.updateDataFromBusinessCardManagement2(scId, wid, this.getValue(), w4ca84254d30c423ab8e449171a5b5123, searchScreen);
	}
	public void updateFromState3(String scId, String wid, int state, String company_, String representative_, String position_, String establish_, String address1_, String address2_, String business1_, String business2_, String companydetail_, String URL_, String contactPerson1_, String position1_, String tel1_, String email1_, String contactPerson2_, String position2_, String tel2_, String email2_, String contactPerson3_, String position3_, String tel3_, String email3_, String contactPerson4_, String position4_, String tel4_, String email4_) {
        Map<String, BusinessCardManagementElement> temp_if16;
        if ((state==0)&&!company_.isEmpty()) {
            String w2d109ad3739d4744a1874ac179fc38b9 = this.w2d109ad3739d4744a1874ac179fc38b9.getValue();
            String companyList = this.companyList.getValue();
            this.widget = screenTemplates.getScreenTemplate(companyList).getWidgets1().getWidget1(w2d109ad3739d4744a1874ac179fc38b9);
            String prevCompany = this.widget.getText();
            if (!company_.equals(prevCompany)) {
                if (this.value.containsKey(company_)) {
                    JPanel mainPanel = screen.getPresenter().getMainPanel();
                    JOptionPane.showMessageDialog(mainPanel, "会社名は既に存在します。");
                } else {
                    this.value.remove(prevCompany);
                    this.value.put(company_, new BusinessCardManagementElement(representative_, position_, establish_, address1_, address2_, business1_, business2_, companydetail_, URL_, contactPerson1_, position1_, tel1_, email1_, contactPerson2_, position2_, tel2_, email2_, contactPerson3_, position3_, tel3_, email3_, contactPerson4_, position4_, tel4_, email4_));
                }
            } else {
                this.value.put(company_, new BusinessCardManagementElement(representative_, position_, establish_, address1_, address2_, business1_, business2_, companydetail_, URL_, contactPerson1_, position1_, tel1_, email1_, contactPerson2_, position2_, tel2_, email2_, contactPerson3_, position3_, tel3_, email3_, contactPerson4_, position4_, tel4_, email4_));
            }
            temp_if16 = this.value;
        } else {
            temp_if16 = this.value;
        }
        this.value = temp_if16;
		String searchCriteriaScreen = this.searchCriteriaScreen.getValue();
		String result = this.result.getValue();
		this.widget = screenTemplates.getScreenTemplate(searchCriteriaScreen).getWidgets1().getWidget1(result);
		this.widget.updateDataFromBusinessCardManagement(scId, wid, this.getValue(), searchCriteriaScreen, result);
		String w2d109ad3739d4744a1874ac179fc38b9 = this.w2d109ad3739d4744a1874ac179fc38b9.getValue();
		String companyList = this.companyList.getValue();
		this.widget = screenTemplates.getScreenTemplate(companyList).getWidgets1().getWidget1(w2d109ad3739d4744a1874ac179fc38b9);
		this.widget.updateDataFromBusinessCardManagement3(scId, wid, this.getValue(), companyList, w2d109ad3739d4744a1874ac179fc38b9);
		String w4ca84254d30c423ab8e449171a5b5123 = this.w4ca84254d30c423ab8e449171a5b5123.getValue();
		String searchScreen = this.searchScreen.getValue();
		this.widget = screenTemplates.getScreenTemplate(searchScreen).getWidgets1().getWidget1(w4ca84254d30c423ab8e449171a5b5123);
		this.widget.updateDataFromBusinessCardManagement2(scId, wid, this.getValue(), w4ca84254d30c423ab8e449171a5b5123, searchScreen);
	}
	public void addBusinessCardManagement(String scId, String wid, String representative, String position, String establishment, String address1, String address2, String businessDescription1, String businessDescription2, String companyOverview, String URL, String companyName, String contactPerson1, String position1, String tel1, String email1, String contactPerson2, String position2, String tel2, String email2, String contactPerson3, String position3, String tel3, String email3, String contactPerson4, String position4, String tel4, String email4) {
        this.value.put(companyName,new BusinessCardManagementElement(representative, position, establishment, address1, address2, businessDescription1, businessDescription2, companyOverview, URL, contactPerson1, position1, tel1, email1, contactPerson2, position2, tel2, email2, contactPerson3, position3, tel3, email3, contactPerson4, position4, tel4, email4));
		String searchCriteriaScreen = this.searchCriteriaScreen.getValue();
		String result = this.result.getValue();
		this.widget = screenTemplates.getScreenTemplate(searchCriteriaScreen).getWidgets1().getWidget1(result);
		this.widget.updateDataFromBusinessCardManagement(scId, wid, this.getValue(), searchCriteriaScreen, result);
		String w2d109ad3739d4744a1874ac179fc38b9 = this.w2d109ad3739d4744a1874ac179fc38b9.getValue();
		String companyList = this.companyList.getValue();
		this.widget = screenTemplates.getScreenTemplate(companyList).getWidgets1().getWidget1(w2d109ad3739d4744a1874ac179fc38b9);
		this.widget.updateDataFromBusinessCardManagement3(scId, wid, this.getValue(), companyList, w2d109ad3739d4744a1874ac179fc38b9);
		String w4ca84254d30c423ab8e449171a5b5123 = this.w4ca84254d30c423ab8e449171a5b5123.getValue();
		String searchScreen = this.searchScreen.getValue();
		this.widget = screenTemplates.getScreenTemplate(searchScreen).getWidgets1().getWidget1(w4ca84254d30c423ab8e449171a5b5123);
		this.widget.updateDataFromBusinessCardManagement2(scId, wid, this.getValue(), w4ca84254d30c423ab8e449171a5b5123, searchScreen);
	}


	final int COMPANY_NAME_INDEX = 0;
	final int PERSON_NAME_INDEX = 1;
	final int POSITION_INDEX = 2;
	final int ADDRESS_INDEX = 4;
	final int TELL_INDEX = 5;
    public void imports(String curScreen, String wid, int state) {
    	if (state != 0) {
    		return;
    	}
        JPanel mainPanel = screen.getPresenter().getMainPanel();
        JFileChooser fileChooser = new JFileChooser();
        FileNameExtensionFilter filter = new FileNameExtensionFilter("CSVファイル(*.csv)", "csv");
        fileChooser.setFileFilter(filter);
        int result = fileChooser.showOpenDialog(mainPanel);
        if (result == JFileChooser.APPROVE_OPTION) {
        	File selectedFile = fileChooser.getSelectedFile();
        	Map<String, List<List<String>>> businessCardData = new HashMap<>();
        	try {
				List<String> lines = Files.readAllLines(selectedFile.toPath(), CHARSET);
				for (int i = 1; i < lines.size(); i++) {
					String line = lines.get(i);
					String[] value = parseCSV(line);
					String companyName = value[0];
					if (! businessCardData.containsKey(companyName)) {
						businessCardData.put(companyName, new ArrayList<>());
					}
					businessCardData.get(companyName).add(Arrays.asList(value));
				}
				for (var companyName : businessCardData.keySet()) {
					String address = businessCardData.get(companyName).get(0).get(ADDRESS_INDEX);
					String[] names = new String[4];
					String[] positions = new String[4];
					String[] tells = new String[4];
					for (int i = 0; i < Math.min(businessCardData.get(companyName).size(), 4); i++) {
						List<String> data = businessCardData.get(companyName).get(i);
						names[i] = data.get(PERSON_NAME_INDEX);
						positions[i] = data.get(POSITION_INDEX);
						tells[i] = data.get(TELL_INDEX);
					}
					BusinessCardManagementElement bussinessCard
						= new BusinessCardManagementElement("", "", "", address, "", "", "", "", "", names[0], positions[0], tells[0], "", names[1], positions[1], tells[1], "",names[2], positions[2], tells[2], "",names[3], positions[3], tells[3], "");
					value.put(companyName, bussinessCard);
				}
                String searchCriteriaScreen = this.searchCriteriaScreen.getValue();
                String res = this.result.getValue();
                this.widget = screenTemplates.getScreenTemplate(searchCriteriaScreen).getWidgets1().getWidget1(res);
                this.widget.updateDataFromBusinessCardManagement(searchCriteriaScreen, res, this.getValue(), searchCriteriaScreen, res);
                String w2d109ad3739d4744a1874ac179fc38b9 = this.w2d109ad3739d4744a1874ac179fc38b9.getValue();
                String companyList = this.companyList.getValue();
                this.widget = screenTemplates.getScreenTemplate(companyList).getWidgets1().getWidget1(w2d109ad3739d4744a1874ac179fc38b9);
                this.widget.updateDataFromBusinessCardManagement3(companyList, w2d109ad3739d4744a1874ac179fc38b9, this.getValue(), companyList, w2d109ad3739d4744a1874ac179fc38b9);
                String w4ca84254d30c423ab8e449171a5b5123 = this.w4ca84254d30c423ab8e449171a5b5123.getValue();
                String searchScreen = this.searchScreen.getValue();
                this.widget = screenTemplates.getScreenTemplate(searchScreen).getWidgets1().getWidget1(w4ca84254d30c423ab8e449171a5b5123);
                this.widget.updateDataFromBusinessCardManagement2(searchScreen, w4ca84254d30c423ab8e449171a5b5123, this.getValue(), w4ca84254d30c423ab8e449171a5b5123, searchScreen);
//                screen.getPresenter().setTable(companyList, w2d109ad3739d4744a1874ac179fc38b9.getValue(), getValue());
			} catch (IOException e) {
				e.printStackTrace();
				JOptionPane.showMessageDialog(mainPanel, "ファイルの取り込みに失敗しました。");
			}
        }
    }
    
    private String[] parseCSV(String line) {
    	 List<String> result = new ArrayList<>();
         StringBuilder field = new StringBuilder();

         boolean inQuotes = false;
         boolean escape = false;

         for (int i = 0; i < line.length(); i++) {
             char c = line.charAt(i);

             if (escape) {
                 field.append(c);
                 escape = false;
                 continue;
             }

             if (c == '\\') {
                 escape = true;
                 continue;
             }

             if (c == '"') {
                 inQuotes = !inQuotes;
                 continue;
             }

             if (c == ',' && !inQuotes) {
                 result.add(field.toString());
                 field.setLength(0);
                 continue;
             }

             field.append(c);
         }

         result.add(field.toString());

         return result.toArray(new String[0]);
     }

    public void load() {
    	try {
			Path path = getCSVFilePath();
			if (Files.notExists(path)) {
				return;
			}
			List<String> lines = Files.readAllLines(path, CHARSET);
			for (String line : lines) {
				String[] values = parseCSV(line);

				BusinessCardManagementElement businessCard = new BusinessCardManagementElement(
			        values[1],
			        values[2],
			        values[3],
			        values[4],
			        values[5],
			        values[6],
			        values[7],
			        values[8],
			        values[9],
			        values[10],
			        values[11],
			        values[12],
			        values[13],
			        values[14],
			        values[15],
			        values[16],
			        values[17],
			        values[18],
			        values[19],
			        values[20],
			        values[21],
			        values[22],
			        values[23],
			        values[24],
			        values[25]
			    );
				value.put(values[0], businessCard);
			}
            String searchCriteriaScreen = this.searchCriteriaScreen.getValue();
            String result = this.result.getValue();
            this.widget = screenTemplates.getScreenTemplate(searchCriteriaScreen).getWidgets1().getWidget1(result);
            this.widget.updateData(this.getValue());
            String w2d109ad3739d4744a1874ac179fc38b9 = this.w2d109ad3739d4744a1874ac179fc38b9.getValue();
            String companyList = this.companyList.getValue();
            this.widget = screenTemplates.getScreenTemplate(companyList).getWidgets1().getWidget1(w2d109ad3739d4744a1874ac179fc38b9);
            this.widget.updateData(this.getValue());
            String w4ca84254d30c423ab8e449171a5b5123 = this.w4ca84254d30c423ab8e449171a5b5123.getValue();
            String searchScreen = this.searchScreen.getValue();
            this.widget = screenTemplates.getScreenTemplate(searchScreen).getWidgets1().getWidget1(w4ca84254d30c423ab8e449171a5b5123);
            this.widget.updateData(this.getValue());
//			screen.getPresenter().setTable(companyList, w2d109ad3739d4744a1874ac179fc38b9.getValue(), getValue());
		} catch (URISyntaxException | IOException e) {
			// TODO 自動生成された catch ブロック
			e.printStackTrace();
		}
    }

    public void save(String curScreen, String wid, int state) {
    	if (state != 0) {
    		return;
    	}
        JPanel mainPanel = screen.getPresenter().getMainPanel();
        Path path;
		try {
			path = getCSVFilePath();
			StringBuilder sb = new StringBuilder();
			if (Files.notExists(path)) {
				Files.createFile(path);
			}
			for (String key : value.keySet()) {
				BusinessCardManagementElement businessCard = value.get(key);
				String[] values = {
						key,
				        businessCard.getRepresentative(),
				        businessCard.getPosition(),
				        businessCard.getEstablishment(),
				        businessCard.getAddress1(),
				        businessCard.getAddress2(),
				        businessCard.getBusinessDescription2(),
				        businessCard.getBusinessDescription1(),
				        businessCard.getCompanyOverview(),
				        businessCard.getURL(),
				        businessCard.getContactPerson1(),
				        businessCard.getPosition1(),
				        businessCard.getTel1(),
				        businessCard.getEmail1(),
				        businessCard.getContactPerson2(),
				        businessCard.getPosition2(),
				        businessCard.getTel2(),
				        businessCard.getEmail2(),
				        businessCard.getContactPerson3(),
				        businessCard.getPosition3(),
				        businessCard.getTel3(),
				        businessCard.getEmail3(),
				        businessCard.getContactPerson4(),
				        businessCard.getPosition4(),
				        businessCard.getTel4(),
				        businessCard.getEmail4()
			    };
				for (String value : values) {
			        if (value != null) {
			            sb.append(escapeCsv(value));
			        }
			        sb.append(",");
			    }
		        sb.deleteCharAt(sb.length() - 1);
			    sb.append('\n');
			}
			sb.deleteCharAt(sb.length() - 1);
			System.out.println(sb.toString());
			Files.write(path, sb.toString().getBytes(CHARSET));
		} catch (URISyntaxException | IOException e) {
			e.printStackTrace();
			JOptionPane.showMessageDialog(mainPanel, "ファイルの保存に失敗しました。");
		}
    }

    private String escapeCsv(String value) {
        if (value.contains(",") || value.contains("\"") || value.contains("\n")) {
            value = value.replace("\"", "\"\"");
            return "\"" + value + "\"";
        }
        return value;
    }

    public void delete(String curScreen, String wid, int state, String key) {
        if (state == 0) {
            this.value.remove(key);
            String searchCriteriaScreen = this.searchCriteriaScreen.getValue();
            String result = this.result.getValue();
            this.widget = screenTemplates.getScreenTemplate(searchCriteriaScreen).getWidgets1().getWidget1(result);
            this.widget.updateDataFromBusinessCardManagement(searchCriteriaScreen, result, this.getValue(), searchCriteriaScreen, result);
            String w2d109ad3739d4744a1874ac179fc38b9 = this.w2d109ad3739d4744a1874ac179fc38b9.getValue();
            String companyList = this.companyList.getValue();
            this.widget = screenTemplates.getScreenTemplate(companyList).getWidgets1().getWidget1(w2d109ad3739d4744a1874ac179fc38b9);
            this.widget.updateDataFromBusinessCardManagement4(companyList, w2d109ad3739d4744a1874ac179fc38b9, this.getValue());
            String w4ca84254d30c423ab8e449171a5b5123 = this.w4ca84254d30c423ab8e449171a5b5123.getValue();
            String searchScreen = this.searchScreen.getValue();
            this.widget = screenTemplates.getScreenTemplate(searchScreen).getWidgets1().getWidget1(w4ca84254d30c423ab8e449171a5b5123);
            this.widget.updateDataFromBusinessCardManagement2(searchScreen, w4ca84254d30c423ab8e449171a5b5123, this.getValue(), w4ca84254d30c423ab8e449171a5b5123, searchScreen);
        }
    }

    private Path getCSVFilePath() throws URISyntaxException {
    	return Paths.get(Main.class.getProtectionDomain()
		        .getCodeSource()
		        .getLocation()
		        .toURI().toString().substring(6) + "../startup.csv");
    }

}