# 2018-Sep-07. Created by Maxim T. 
function GetSymbolInfo($symbolLine, $quotesFolder, $minDate)
{ # Parsing symbol line in psConfig.txt file: # Yahoo: list of symbols from Yahoo Finance website. Format: Symbol,MinDate,MaxDate,IntraDayFlag[Y|N],[DividendFlag[Y|N],FactorHistory,FactorIntraDay,FactorDividend
    $logFunc = "";
    $s = $symbolLine.Split(","); # Splitting symbol line by comma
    $symbol = $s[0]; $symbolMinDate = $s[1]; $symbolMaxDate = $s[2]; $symbolIntradayFlag = $s[3]; $symbolDividendFlag = $s[4];
    $symbolQuoteFile = $quotesFolder + "_" + $symbol.Replace(":","_").Replace("^","_").Replace("&","_") + "_" + ".txt"; # Symbol file were quotes will be saved. Adding "_" in front of symbol names as sometimes sequences like \PRN or \CON means something....
    $logFunc += (Get-Date).ToString("HH:mm:ss") + " Symbol: " + $symbol.PadRight(20)
    if ($symbolMinDate -ne "" -and $symbolMinDate -ne $null -and ($symbolMinDate.length -ne 10 -or $symbolMinDate -le "1950-01-01" -or $symbolMinDate -gt "2050-01-01")) {$symbolMinDate = ""; $logFunc+="Symbol $symbol MinDate specified is not correct, so specified value will be ignored.";}
    if ($symbolMaxDate -ne "" -and $symbolMaxDate -ne $null -and ($symbolMaxDate.length -ne 10 -or $symbolMaxDate -le "1950-01-01" -or $symbolMaxDate -gt "2050-01-01")) {$symbolMaxDate = ""; $logFunc+="Symbol $symbol MaxDate specified is not correct, so specified value will be ignored.";}
    if ($symbolMinDate -eq "" -or  $symbolMinDate -eq $null -or  $symbolMinDate -lt $minDate) {$symbolMinDate = $minDate;}
    if ($symbolMaxDate -eq "" -or  $symbolMaxDate -eq $null) {$symbolMaxDate = (Get-Date).AddDays(1).ToString("yyyy-MM-dd");} # Time difference - you might be in Australia requesting USA quotes
    $symbolMaxDateAdj = ([datetime]::ParseExact($symbolMaxDate,"yyyy-MM-dd",$null)).AddDays(10).ToString("yyyy-MM-dd"); # Will try to save up to 10 more days than request, because specific day quote might not be available (ex: weekend), so we would request more quotes even when not required
    $nextDate = $symbolMinDate;
    if (Test-Path -Path $symbolQuoteFile) { # File exists, need to find last available quote date
        $fc = @(import-csv $symbolQuoteFile -Header "Date","Close","Symbol" | Sort-Object -Property "Date"); 
        $lastDateInFile=""; if ($fc.count -gt 0) {$lastDateInFile = $fc[$fc.count-1].Date;} if ($lastDateInFile -eq $null) {$lastDateInFile = "";} # Finding max quote date in file.Format will be YYYY-MM-DD
        if ($lastDateInFile -ne "") { # File exists and max date in the file found
            $nextDate = ([datetime]::ParseExact($lastDateInFile,"yyyy-MM-dd",$null)).AddDays(1).ToString("yyyy-MM-dd"); # Adding one day to max date found in quote file - this will be next request start date
            $logFunc+="  Found quote file. Looking for quotes starting from: $nextDate"
        }
    }
    $lastQuote = ([datetime]::ParseExact($nextDate,"yyyy-MM-dd",$null)).AddDays(-1).ToString("yyyy-MM-dd");
    # Returning following values:
    $symbol;            # 0
    $nextDate;          # 1 
    $symbolMaxDate;     # 2 
    $symbolMaxDateAdj;  # 3
    $symbolQuoteFile;   # 4 
    $lastQuote          # 5
}

function GetSymbolLastDateInFile($symbol, $quotesFolder, $minDate) {
    $lastDateInFile = ([datetime]::ParseExact($minDate,"yyyy-MM-dd",$null)).AddDays(-1).ToString("yyyy-MM-dd"); # Last day in file is day before MinDate
    $symbolQuoteFile = $quotesFolder + "_" + $symbol.Replace(":","_").Replace("^","_").Replace("&","_") + "_" + ".txt"; # Symbol file were quotes will be saved. Adding "_" in front of symbol names as sometimes sequences like \PRN or \CON means something....
    if (Test-Path -Path $symbolQuoteFile) { # File exists, need to find last available quote date
        $fc = @(import-csv $symbolQuoteFile -Header "Date","Close","Symbol" | Sort-Object -Property "Date"); 
        $ld=""; if ($fc.count -gt 0) {$ld = $fc[$fc.count-1].Date;} if ($ld -eq $null) {$ld = "";} # Finding max quote date in file.Format will be YYYY-MM-DD
        if (!(($ld -eq "" -or $ld -eq $null))) {$lastDateInFile = $ld;}
    }
    return($lastDateInFile);
}


function GetCurrExchInfo($currFrom, $currTo, $currExchFolder, $minDate)
{ 
    $currExchFile = $currExchFolder + $currFrom + "_" + $currTo + ".txt";
    $nextDate = $minDate;
    # Getting date of last quote for currency group in quote file we already have. If there is no quote file, use min date from parameter file
    if (Test-Path -Path $currExchFile) { # File exists, need to find last available quote date
        $fc = @(import-csv $currExchFile -Header "Date","Rate","CurrFrom","CurrTo" | Sort-Object -Property "Date"); $lastDateInFile=""; if ($fc.count -gt 0) {$lastDateInFile = $fc[$fc.count-1].Date;}
        if ($lastDateInFile -ne "") { $nextDate = ([datetime]::ParseExact($lastDateInFile,"yyyy-MM-dd",$null)).AddDays(1).ToString("yyyy-MM-dd");} # Adding one day to max date found in quote file - this will be next request start date
    }
    $lastQuote = ([datetime]::ParseExact($nextDate,"yyyy-MM-dd",$null)).AddDays(-1).ToString("yyyy-MM-dd");
    $currExchFile; # 0
    $nextDate;     # 1
    $lastQuote;    # 2
}

function GetTxtBetween($txtSearch, $startTxt, $endTxt)
{
 $txtBetween=""; $txt = $txtSearch;
 if($txt.Contains($startTxt)) {
    $txt = $txt.PadRight(1000).Substring($txt.IndexOf($startTxt) + $startTxt.Length, 100).TrimEnd();
    #if ($txt.Length -gt 100) {$txt = $txt.Substring(0, 99);}
    if ($txt.Contains($EndTxt)) {
        $txtBetween = $txt.Substring(0, $txt.IndexOf($endTxt));
    }
 }
 $txtBetween; # Returns one result
}


#cls
#GetSymbolInfo "HD.US" "C:\VidasSvarbu\Dropbox\PortfolioSlicer\PSDataExtract\Quotes\" "2006-12-30"
#GetSymbolInfo "HD.US,2010-10-07,,Y,N,,," "C:\VidasSvarbu\Dropbox\PortfolioSlicer\PSDataExtract\Quotes\" "2006-12-30"

#cls
#$d=GetSymbolLastDateInFile "CCL" "C:\VidasSvarbu\Dropbox\PortfolioSlicer\PSDataExtract\Quotes\" "2006-12-30"


#"psFunctions start";
#$nextDate = "";
#$ret = GetSymbolInfo "CCL1,2014-10-07,,Y,N,,," "C:\VidasSvarbu\Dropbox\PortfolioSlicer\PSDataExtract\Quotes\" "2006-12-30"
#"NextDate: " + $ret[0] + ". File: " + $ret[1];
#"Log: " + $ret[2]
#exit(1);

# $lastDateInFile = "";
#    if ($nextDate -gt $symbolMaxDate) { # For this symbol we already have localy data up to Max date.
#        "  We already have data up to maximum configuration date of $symbolMaxDate. Will not request new data for this symbol." | Out-File $logFile -Encoding OEM -Append; 
#        #$log + " Local file has all necessary data."; 
#        continue; 
#    } 
    
