use hahn;
pragma yt.Pool="robot-webmaster";

$units = 30.0;

$table_input        = "//home/webmaster/prod/analytics/catalogia/bs-chevent-log";
$table_output_abs   = "//home/webmaster/prod/analytics/catalogia/chart-absolute";
$table_output_shr   = "//home/webmaster/prod/analytics/catalogia/chart-share";

$total = (
    select
        period,
        sum(units) * $units as total
    from $table_input
    group by DateTime::MakeDate(DateTime::StartOfWeek(cast(period as Date))) as period
);

$sources = (
    select
        period,
        coalesce(sum_if(units, simdistance == "700010") * $units, 0.0) as D_700010,
        coalesce(sum_if(units, simdistance == "700050") * $units, 0.0) as D_700050,
        coalesce(sum_if(units, simdistance == "700333") * $units, 0.0) as D_700333,
        coalesce(sum_if(units, simdistance == "804050") * $units, 0.0) as S_804050,
        coalesce(sum_if(units, simdistance == "800333") * $units, 0.0) as S_800333,
        coalesce(sum_if(units, simdistance == "700025") * $units, 0.0) as D_700025,
        coalesce(sum_if(units, simdistance == "804002") * $units, 0.0) as S_804002,
        coalesce(sum_if(units, simdistance == "700003") * $units, 0.0) as D_700003,
        coalesce(sum_if(units, simdistance == "800002") * $units, 0.0) as S_800002,
    from $table_input
    group by DateTime::MakeDate(DateTime::StartOfWeek(cast(period as Date))) as period
);

insert into $table_output_shr
    with truncate
select 
    t.period as Period,
    s.D_700003 / t.total as D_700003,
    s.D_700010 / t.total as D_700010,
    s.D_700050 / t.total as D_700050,
    s.D_700333 / t.total as D_700333,
    s.S_800002 / t.total as S_800002,
    s.S_804050 / t.total as S_804050,
    s.S_800333 / t.total as S_800333,
    (s.D_700010 + s.D_700050 + s.D_700333 + s.S_800333 + s.S_804050 + D_700003 + S_800002) / t.total as ShareTotal,
    (s.D_700010 + s.D_700050 + s.D_700333 + s.S_800333 + s.S_804050 + D_700003 + S_800002) / (t.total - s.S_804002 - s.D_700025) as ShareStable1,
from $total as t
inner join $sources as s
    on t.period == s.period
order by Period;

insert into $table_output_abs
    with truncate
select 
    t.period as Period,
    s.D_700003 as D_700003,
    s.D_700010 as D_700010,
    s.D_700050 as D_700050,
    s.D_700333 as D_700333,
    s.S_800002 as S_800002,
    s.S_804050 as S_804050,
    s.S_800333 as S_800333,
    s.D_700025 as Stable1,
    s.S_804002 as Stable2,
    t.total as Total,
    t.total - s.D_700025 - s.S_804002 as TotalStable,
    s.D_700010 + s.D_700050 + s.D_700333 + s.S_800333 + s.S_804050 + s.D_700003 + s.S_800002 as TotalWMC
from $total as t
inner join $sources as s
    on t.period == s.period
order by Period;
