AWSTemplateFormatVersion: '2010-09-09'
Transform: 'AWS::Serverless-2016-10-31'
Metadata:
  AWS::CloudFormation::Interface:
    ParameterGroups:
      -
        Label:
          default: "Amazon Connect"
        Parameters:
          - ConnectInstanceId
      - Label:
          default: "DynamoDB"
        Parameters:
          - TableName
      - Label:
          default: "Lambda"
        Parameters:
          - DateFormat
          - TimeZone
    ParameterLabels:
      ConnectInstanceId:
        default: "Connect Instance Id"
      TableName:
        default: "Holiday Table Name"
      DateFormat:
        default: "Date Format"
      TimeZone:
        default: "Time Zone"

Parameters:
  ConnectInstanceId:
    Type: String
    Description: The Amazon Connect Instance Id
    Default: "****Enter your Amazon Connect Instance Id****"
  TableName:
    Type: String
    Description: The name for our Holiday table in DynamoDB
    Default: "Holidays"
  DateFormat:
    Type: String
    AllowedValues:
      - DDMMYYYY
      - MMDDYYYY
      - YYYYMMDD
      - YYYYDDMM
    Description: The format for the date.
    Default: "DDMMYYYY"
  TimeZone:
    Type: String
    Description: The IANA name for our Time Zone. See https://en.wikipedia.org/wiki/List_of_tz_database_time_zones
    Default: "Asia/Singapore"
Resources:
  HolidaysTable:
    Type: AWS::DynamoDB::Table
    Properties:
      AttributeDefinitions:
      - AttributeName: FullDate
        AttributeType: S
      KeySchema:
      - AttributeName: FullDate
        KeyType: HASH
      ProvisionedThroughput:
        ReadCapacityUnits: '5'
        WriteCapacityUnits: '5'
      TableName: !Sub ${TableName}

  RootRolereadholiday:
    Type: 'AWS::IAM::Role'
    Properties:
      RoleName: !Sub ${AWS::Region}-readholiday-iam-role
      AssumeRolePolicyDocument:
        Version: 2012-10-17
        Statement:
          - Effect: Allow
            Principal:
              Service:
                - lambda.amazonaws.com
            Action:
              - 'sts:AssumeRole'
      Path: /
  RolePolicieslogreadholiday1:
    Type: 'AWS::IAM::ManagedPolicy'
    Properties:
      ManagedPolicyName: !Sub ${AWS::Region}-readholiday-log-policy
      PolicyDocument:
        Version: 2012-10-17
        Statement:
        - Effect: Allow
          Action:
          - logs:CreateLogStream
          - logs:PutLogEvents
          - logs:CreateLogGroup
          Resource:
          - !Sub 'arn:${AWS::Partition}:logs:${AWS::Region}:${AWS::AccountId}:*'
      Roles:
      - !Ref RootRolereadholiday
  RolePoliciesreadholiday1:
    Type: 'AWS::IAM::ManagedPolicy'
    Properties:
      ManagedPolicyName: !Sub ${AWS::Region}-readholiday-iam-policy
      PolicyDocument:
        Version: 2012-10-17
        Statement:
        - Effect: Allow
          Action:
          - 'dynamodb:UpdateGlobalTableSettings'
          - 'dynamodb:GetItem'
          - 'dynamodb:Scan'
          - 'dynamodb:Query'
          - 'dynamodb:GetRecords'
          Resource:
          - !Sub 'arn:${AWS::Partition}:dynamodb:${AWS::Region}:${AWS::AccountId}:table/${TableName}'
      Roles:
      - !Ref RootRolereadholiday
  RootInstanceProfilereadholiday:
    Type: 'AWS::IAM::InstanceProfile'
    Properties:
      Path: /
      Roles:
        - !Ref RootRolereadholiday
  Lambdareadholiday:
    Type: 'AWS::Serverless::Function'
    DependsOn: RootRolereadholiday
    Properties:
      FunctionName: readholiday
      Handler: index.handler
      Runtime: nodejs12.x
      InlineCode: |
        const AWS = require('aws-sdk');
        const docClient = new AWS.DynamoDB.DocumentClient();
        process.env.TZ = process.env.TimeZone; //Set the correct timezone for your call centre
        exports.handler = (event, context, callback) => {
            let fullDate
            let d = new Date();
            let dateDay = new Date(d).getDate().toString();
            if (dateDay < 10) { //Normalise day format to XX e.g. Jan 1 becomes Jan 01
                dateDay = "0" + dateDay;
            }
            let dateMonth = new Date(d).getMonth() + 1;
            if (dateMonth < 10) { //Normalise month format to XX e.g. Frbruary becomes 02
                dateMonth = "0" + dateMonth;
            }
            let dateYear = new Date(d).getFullYear().toString(); //THis is in XXXX format
            switch (process.env.DateFormat) {
            case "DDMMYYYY":
              fullDate = dateDay + dateMonth + dateYear;
              console.log("Today's date is " + dateDay + "/"+ dateMonth + "/" + dateYear + " converted to " + fullDate);
              break;
            case "MMDDYYYY":
              fullDate = dateMonth + dateDay + dateYear;
              console.log("Today's date is " + dateMonth + "/" + dateDay + "/" + dateYear + " converted to " + fullDate);
              break;
            case "YYYYMMDD":
              fullDate = dateYear + dateMonth + dateDay;
              console.log("Today's date is " + dateYear + "/" + dateMonth + "/" + dateDay + " converted to " + fullDate);
              break;
            case "YYYYDDMM":
              fullDate = dateYear + dateDay + dateMonth;
              console.log("Today's date is " + dateYear + "/" + dateDay + "/"+ dateMonth + " converted to " + fullDate);
              break;
            }
            
            const params = {
                TableName: process.env.TableName,
                KeyConditionExpression: "FullDate = :fullDate",
                ExpressionAttributeValues: {
                    ":fullDate": fullDate
                }
            };
            docClient.query(params, function(err, data) {

                if (err) {
                    callback(err, null);
                }
                else {
                    if (data.Items[0] == null) {
                        const noHolidayResponse = JSON.stringify({ publicHoliday: 'false' });
                        callback(null, JSON.parse(noHolidayResponse));
                    }
                    else {
                        if (!data.Items[0].HolidayName){
                            data.Items[0].HolidayName = "blank";
                        }
                        const holidayResponse = JSON.stringify({ publicHoliday: 'true', holidayName: data.Items[0].HolidayName });
                        callback(null, JSON.parse(holidayResponse));
                    }
                }
            });
        };
      Description: ''
      MemorySize: 1024
      Timeout: 8
      Role: !Sub 'arn:${AWS::Partition}:iam::${AWS::AccountId}:role/${AWS::Region}-readholiday-iam-role'
      Environment:
        Variables:
          TableName: !Sub ${TableName}
          TimeZone: !Sub ${TimeZone}
          DateFormat: !Sub ${DateFormat}
  ConnectFunctionPolicyLambdareadholiday:
    Type: AWS::Lambda::Permission
    DependsOn: Lambdareadholiday
    Properties:
      FunctionName: !Sub 'readholiday'
      Action: "lambda:InvokeFunction"
      Principal:  "connect.amazonaws.com"
      SourceAccount: !Sub ${AWS::AccountId}
      SourceArn: !Sub arn:${AWS::Partition}:connect:${AWS::Region}:${AWS::AccountId}:instance/${ConnectInstanceId}
