package com.zimmerbell.repaper.sources;

import java.io.File;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;

import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.zimmerbell.repaper.Source;

public class MomentumSource implements Source {
	
	private static final Logger LOG = LoggerFactory.getLogger(MomentumSource.class);
	
	private final static String CHROME_FOLDER = System.getenv("LOCALAPPDATA") + "\\Google\\Chrome\\User Data\\Default";
	private final static String EXTENSION_ID = "laookkfknpbbblfpciffpaejjkokdgca";
	private final static String SQLITE_FILE = CHROME_FOLDER + "\\Local Storage\\chrome-extension_" + EXTENSION_ID + "_0.localstorage";
	
	
	private JSONObject data;
	
	private String getSqliteFile() {
		return SQLITE_FILE;
	}
	
	private String getChromeProfileFolder() {
		return CHROME_FOLDER;
	}
	
	public boolean exists(){
		File file = new File(getSqliteFile());
		return file.exists() && file.length() > 0;
	}

	@Override
	public void update() throws Exception {
		
		data = new JSONObject();
		
		Class.forName("org.sqlite.JDBC");
		Connection connection = DriverManager.getConnection("jdbc:sqlite:" + getSqliteFile());
		
		try(Statement stmt = connection.createStatement()){
			
			String today = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
			
			try(ResultSet rs = stmt.executeQuery("SELECT * FROM ItemTable WHERE Key='momentum-background-" + today + "' ORDER BY Key DESC LIMIT 1")){
				if(!rs.next()){
					return;
				}
				String key = rs.getString("Key");
				LOG.info(key);
				
				data = new JSONObject(rs.getString("Value"));
				LOG.info(data.toString());
			}
			
		}
	}
	
	private String getData(String key) throws Exception {
		if (data == null) {
			update();
		}
		try{
			return data.getString(key);
		}catch(JSONException e){
			return null;
		}
	}

	@Override
	public String getImageUri() throws Exception {
		String filename = getData("filename");
		if(filename != null && !filename.startsWith("http")){
			File[] files = new File(getChromeProfileFolder() + File.separator + "Extensions" + File.separator + EXTENSION_ID).listFiles();
			Arrays.sort(files);
			String extensionHome = files[files.length - 1].getAbsolutePath();
			
			filename = extensionHome + File.separator + filename;
		}
		return filename;
	}

	@Override
	public String getTitle() throws Exception {
		return getData("title");
	}

	@Override
	public String getBy() throws Exception {
		return getData("source");
	}

	@Override
	public String getDetailsUri() throws Exception {
		return getData("sourceUrl");
	}

}

@@ -578,22 +578,24 @@
  CHROME_
-FOLDER
+PROFILES
  = Syste
@@ -653,17 +653,8 @@
 Data
-%5C%5CDefault
 %22;%0A%09
@@ -776,26 +776,15 @@
 FILE
- = CHROME_FOLDER +
+_PATH =
  %22%5C%5C
@@ -870,88 +870,499 @@
 ate 
-JSONObject data;%0A%09%0A%09private String getSqlite
+String chromeProfileFolder;%0A%09private JSONObject data;%0A%09%0A%09public MomentumSource() %7B%0A%09%09long t = 0;%0A%09%09for(File profileFolder : new File(CHROME_PROFILES).list
 File
+s
 ()
+)
  %7B%0A%09%09
-return SQLITE_FILE
+%09File sqliteFile = new File(profileFolder, SQLITE_FILE_PATH);%0A%09%09%09if(sqliteFile.exists() && sqliteFile.length() %3E 0 && (t %3C sqliteFile.lastModified())) %7B%0A%09%09%09%09t = sqliteFile.lastModified();%0A%09%09%09%09chromeProfileFolder = profileFolder.getAbsolutePath();%0A%09%09%09%7D%0A%09%09%7D%0A%09%09LOG.info(%22using chrome profile: %7B%7D%22, chromeProfileFolder)
 ;%0A%09%7D%0A%09%0A
+%09%0A
 %09pri
@@ -1413,138 +1413,274 @@
 urn 
-CHROME_FOLDER;%0A%09%7D%0A%09%0A%09public boolean exists
+chromeProfileFolder;%0A%09%7D%0A%09%0A%09private String getSqliteFile
 ()
+ 
 %7B%0A%09%09
-File file = new File(getSqliteFile());%0A%09%09return file.exists() && file.length() %3E 0
+String chromeProfileFolder = getChromeProfileFolder();%0A%09%09return chromeProfileFolder == null ? null : chromeProfileFolder + SQLITE_FILE_PATH;%0A%09%7D%0A%09%0A%09public boolean exists()%7B%0A%09%09return getSqliteFile() != null
 ;%0A%09%7D
@@ -2767,54 +2767,24 @@
 ) + 
-File.separator + %22Extensions%22 + File.separator
+%22%5C%5CExtensions%5C%5C%22
  + E

support for multi chrome profiles