#cls;
$st = Get-Date;
# 2019-Jan-16. Created by Maxim T. 
$scriptPath = Split-Path -parent $MyInvocation.MyCommand.Definition; 
. ($scriptPath + "\psFunctions.ps1");     # Adding script with reusable functions
. ($scriptPath + "\psSetVariables.ps1");  # Adding script to assign values to common variables

$logFile        = $scriptPath + "\Log\" + $MyInvocation.MyCommand.Name.Replace(".ps1",".txt"); 
(Get-Date).ToString("HH:mm:ss") + " --- Starting script " + $MyInvocation.MyCommand.Name | Out-File $logFile -Encoding OEM; # starting logging to file.
$logSummary = (Get-Date).ToString("HH:mm:ss") + " Script: CalcCostBasis".PadRight(28);

$transFile = $psDataFolder + "\TransactionsInExcel.csv";
$f = Import-CSV -Path $transFile -Delimiter `t | Sort Account,Symbol,Date,@{expression={$_.TransSortOrder -as [int]}};

$outFile = $psDataFolder + "\Transactions.csv";
$fTxt="Account,Date,TransType,TransSubType,Symbol,Qty,Price,Fee,ExchRate,CostBasisOverride,ExchRateRpt1Override,ExchRateRpt2Override,ExchRateRpt3Override,TransID,CostBasisImpact".Replace(",",$colSep) | Out-File $outFile -Encoding OEM; #file header

$account=""; $symbol="";$date=Get-Date "1900-01-01"; $runCBI=0; $qhbs=0; $accCurr="";#starting values
ForEach ($line in $f) {     #reseting to new symbol/account if that set changed
    if ($line.Account.ToLower() -ne $account -or $line.Symbol.ToLower() -ne $symbol) {
        $account = $line.Account.ToLower(); $symbol = $line.Symbol.ToLower(); $runCBI=0; $qhbs=0;
    } 
    $price             = try {[double]::Parse($line.Price)} catch {0}; 
    $fee               = try {[double]::Parse($line.Fee)} catch {0}; 
    $totalAmnt         = try {[double]::Parse($line.TotalAmnt)} catch {0};  
    $costBasisOverride = try {[double]::Parse($line.CostBasisOverride) } catch {0};
    $qtyChg            = try {[double]::Parse($line.QtyChange) } catch {0};

    #$price             = [double]$line.Price;
    #$fee               = [double]$line.Fee; 
    #$totalAmnt         = [double]$line.TotalAmnt;  
    #$costBasisOverride = [double]$line.CostBasisOverride;

    if (-not ($line.BookValueSign -eq 0 -and $qtyChg -eq 0)) { #BookValueSign indicates this transaction does not impact Cost Basis and there is no quantity change (due to split)
        if($line.BookValueSign -eq 0 -or $line.Symbol.ToLower() -eq "* cash") {$cbi = 0;} # cost basis impact is not calculated for this type of transaction
        else {if ($line.CostBasisOverride.Trim() -ne "") {$cbi = $costBasisOverride * [double] $line.BookValueSign;} # found CostBasisOverride, so using provided value for CB Impact
              else {if ($line.BookValueSign -eq 1 -or $qtyChg -eq 0) {$cbi = $totalAmnt * [double]$line.BookValueSign;} # this is CB increase, so just use TotalAmnt (signed)
                    else { 
                            if($qhbs-eq 0) {"TransID:" + $line.TransID + " quantity held before sales is 0."; $cbi = 0} # If sale is before buy, then quantity held before sale will be 0, so we calculate CostBasisImpact=0
                            else {$cbi =  [math]::Round($runCBI / $qhbs * $qtyChg, 2);}} # calculating by using formula: CBPerShare * SharesSold; CBPerShare = running CostBasis dividing by shares holding to date (before this trans)
                   }
             }
        $line.CostBasisImpact = $cbi;   # writing back Cost Basis Impact value into CSV data set
        $runCBI+=$cbi;          # adjusting running cost basis impact with new calculated cost basis impact
        $qhbs+=$qtyChg; # adjusting AFTER transaction $cbi is calculated
    }


    #if ($line.Symbol.ToLower() -eq "tdb8150" -and $line.Account.ToLower() -eq "joint-cdn" -and $line.TransType.ToLower() -ne "divta") {
    #  $line.Date + $colSep + $line.TransType + $colSep + $line.Qty + $colSep + $line.Price + $colSep + $line.TransID 
    #  $line.CostBasisImpact;
    #  if ($line.TransID -eq 5806) {exit(1)}
    #}

    $cbN = [math]::Round($line.CostBasisImpact,4); 
    if ($decSep -eq ",") {$cbStr= $cbN.ToString("########0.0###", $culture2);} else {$cbStr= $cbN.ToString("########0.0###", $culture);}
    $fTxt += $line.Account + $colSep + $line.Date + $colSep + $line.TransType + $colSep + $line.TransSubType + $colSep + $line.Symbol + $colSep + $line.Qty `
            + $colSep + $line.Price + $colSep + $line.Fee + $colSep + $line.ExchRate + $colSep + $line.CostBasisOverride `
            + $colSep + $line.ExchRateRpt1Override + $colSep + $line.ExchRateRpt2Override + $colSep + $line.ExchRateRpt3Override + $colSep + $line.TransID `
            + $colSep + $cbStr + $eol;
            #+ $colSep + [math]::Round($line.CostBasisImpact,4).ToString("########0.0###", $culture)  + $eol;

#+ $colSep + $line.TotalAmnt + $colSep + $line.QtyChange  
#    if ([math]::Round($line.CostBasisImpact,1) -ne [math]::Round($line.CBIInExcel,1)) {
#        "For TransID: " + $line.TransID.ToString() + " CBI and CBIInExcel does not match. CBI: " + $line.CostBasisImpact.ToString() + ".`t CBIInExcel: " + $line.CBIInExcel.ToString() + ". Account: '$account'. Symbol: '$symbol'"; 
#    }
}
# Saving to file after each currency
$fTxt = $fTxt.Substring(0, $fTxt.Length-$eol.Length); # Removing last 2 characters that are end of line
$fTxt | Out-File $outFile -Encoding OEM -Append; #output file


#$f | Select-Object Account, Date, TransType, TransSubType, Symbol, Qty, Price, Fee, TotalAmnt, QtyChange, CostBasisImpact | Export-Csv -Path $outFile -Delimiter `t -NoTypeInformation
# (([double]$d[1]) * $factor).ToString("########0.0######", $culture).Replace(".",$decSep)

$duration = (NEW-TIMESPAN -Start $startTime -End (Get-Date)).TotalSeconds.ToString("#,##0") + " sec.";
(Get-Date).ToString("HH:mm:ss") + " --- Finished CalcCostBasis. Duration: $duration`r`n" | Out-File $logFile -Encoding OEM -append;
$logSummary + ". Duration: $duration";

