--[[----------------------------------------------------------------------------

WFJsonValidatorTest.lua

--------------------------------------------------------------------------------

ADOBE CONFIDENTIAL
------------------
Copyright 2016 Adobe Systems Incorporated
All Rights Reserved.

NOTICE: All information contained herein is, and remain the property of
Adobe Systems Incorporated and its suppliers, if any. The intellectual and
technical concepts contained herein are proprietary to Adobe Systems
Incorporated and its suppliers and may be covered by U.S. and Foreign
Patents, patents in process, and are protected by trade secret or copyright
law.  Dissemination of this information or reproduction of this material is
strictly forbidden unless prior written permission is obtained from
Adobe Systems Incorporated.

------------------------------------------------------------------------------]]

	-- WF.core.self_test
local WFRxTestCase = require 'WFRxTestCase'

local WFJsonValidator = require 'WFJsonValidatorImp'

--============================================================================--

local WFJsonValidatorTest = {}

--------------------------------------------------------------------------------

local xmpSchema = [[
{
  "$schema": "http://json-schema.org/draft-04/schema#iso8601-date-time",
  "title": "xmp schema",
  "type": "object",
  "definitions": {
    "adobe-fi": {
      "type": "object",
      "properties": {
        "FaceID": {
          "$ref": "#/definitions/uuid"
        },
        "Timestamp": {
          "$ref": "#/definitions/utcDateTime"
        },
        "ConfidenceLevel": {
          "$ref": "#/definitions/oneTo100Integer"
        },
        "People": {
          "type": "array",
          "items": {
            "type": "object",
            "properties": {
              "PersonID": {
                "$ref": "#/definitions/uuid"
              },
              "Confirmed": {
                "type": "boolean"
              },
              "ConfidenceLevel": {
                "$ref": "#/definitions/oneTo100Integer"
              }
            },
            "additionalProperties": false,
            "required": [
              "PersonID"
            ]
          },
          "minItems": 1
        }
      },
      "additionalProperties": false,
      "required": [
        "FaceID"
      ]
    },
    "oneTo100Integer": {
      "type": "integer",
      "minimum": 1,
      "maximum": 100
    },
    "rational": {
      "type": "array",
      "minItems": 2,
      "maxItems": 2,
      "items": {
        "type": "integer"
      }
    },
    "rsArea": {
      "type": "object",
      "properties": {
        "x": {
          "type": "number"
        },
        "y": {
          "type": "number"
        },
        "w": {
          "type": "number"
        },
        "h": {
          "type": "number"
        },
        "d": {
          "type": "number"
        },
        "unit": {
          "enum": [
            "normalized"
          ]
        }
      },
      "additionalProperties": false,
      "required": [
        "x",
        "y",
        "unit"
      ],
      "dependencies": {
        "w": {
          "description": "w and h describe a rectangle, so they must be included together. d describes a circle, so it is mutually exclusive from w and h.",
          "required": [
            "h"
          ],
          "not": {
            "required": [
              "d"
            ]
          }
        },
        "h": {
          "description": "w and h describe a rectangle, so they must be included together. d describes a circle, so it is mutually exclusive from w and h.",
          "required": [
            "w"
          ],
          "not": {
            "required": [
              "d"
            ]
          }
        },
        "d": {
          "description": "d describes a circle, so it is mutually exclusive from w and h, which describe a rectangle.",
          "not": {
            "anyOf": [
              {
                "required": [
                  "w"
                ]
              },
              {
                "required": [
                  "h"
                ]
              }
            ]
          }
        }
      }
    },
    "stringBag": {
      "type": "object",
      "patternProperties": {
        ".+": {
          "enum": [
            true
          ]
        }
      },
      "additionalProperties": false,
      "minProperties": 1
    },
    "stringList": {
      "type": "array",
      "items": {
        "type": "string"
      },
      "minItems": 1
    },
    "utcDateTime": {
      "type": "string",
      "pattern": "^([0-9]{3}[1-9]|[0-9]{2}[1-9][0-9]|[0-9][1-9][0-9]{2}|[1-9][0-9]{3})-((02-([1-2][0-9]|0[1-9]))|((01|03|05|07|08|10|12)-(3[0-1]|[1-2][0-9]|0[1-9]))|((04|06|09|11)-(30|[1-2][0-9]|0[1-9])))T(2[0-3]|[0-1][0-9]):[0-5][0-9]:[0-5][0-9](\\.[0-9]+)?Z$",
      "description": "requires a UTC time ending with Z (so -00:00 or +00-00 suffix NOT allowed)"
    },
    "uuid": {
      "type": "string",
      "pattern": "^[a-f0-9]{32}$"
    },
    "xmpDateTime": {
      "description": "date time in ISO-8601 format with timezone, seconds, time, day and month optional and also allowing some nonstandard timezone formats. Some examples: 2016-01-15T12:10Z, 2016-01-15T12:10:32, 2016-01-15, 2016-04, 2017, 2016-01-15T12:10:32+0000, 2016-01-15T12:10:32-05",
      "type": "string",
      "pattern": "^([0-9]{3}[1-9]|[0-9]{2}[1-9][0-9]|[0-9][1-9][0-9]{2}|[1-9][0-9]{3})(-(((02-([1-2][0-9]|0[1-9]))|((01|03|05|07|08|10|12)-(3[0-1]|[1-2][0-9]|0[1-9]))|((04|06|09|11)-(30|[1-2][0-9]|0[1-9])))(T(2[0-3]|[0-1][0-9]):[0-5][0-9](:[0-5][0-9](\\.[0-9]+)?)?(((\\+|-)(2[0-3]|[0-1][0-9])(:?[0-5][0-9])?)|Z)?)?|(0[1-9]|1[0-2])))?$"
    }
  },
  "properties": {
    "aux": {
      "type": "object",
      "properties": {
        "ApproximateFocusDistance": {
          "$ref": "#/definitions/rational"
        },
        "IsMergedHDR": {
          "type": "boolean"
        },
        "IsMergedPanorama": {
          "type": "boolean"
        },
        "Lens": {
          "type": "string"
        },
        "SerialNumber": {
          "type": "string"
        }
      },
      "additionalProperties": false,
      "minProperties": 1
    },
    "dc": {
      "type": "object",
      "properties": {
        "creator": {
          "$ref": "#/definitions/stringList"
        },
        "subject": {
          "$ref": "#/definitions/stringBag"
        },
        "description": {
          "type": "string"
        },
        "rights": {
          "type": "string"
        },
        "title": {
          "type": "string"
        }
      },
      "additionalProperties": false,
      "minProperties": 1
    },
    "exif": {
      "type": "object",
      "properties": {
        "ApertureValue": {
          "$ref": "#/definitions/rational"
        },
        "BrightnessValue": {
          "oneOf": [
            {
              "$ref": "#/definitions/rational"
            },
            {
              "enum": [
                "unknown"
              ]
            }
          ]
        },
        "DateTimeOriginal": {
          "$ref": "#/definitions/xmpDateTime"
        },
        "ExposureBiasValue": {
          "$ref": "#/definitions/rational"
        },
        "ExposureProgram": {
          "enum": [
            "not defined",
            "manual",
            "normal program",
            "aperture priority",
            "shutter priority",
            "creative program",
            "action program",
            "portrait mode",
            "landscape mode"
          ]
        },
        "ExposureTime": {
          "$ref": "#/definitions/rational"
        },
        "FNumber": {
          "$ref": "#/definitions/rational"
        },
        "FlashFired": {
          "type": "boolean"
        },
        "FlashFunction": {
          "type": "boolean"
        },
        "FlashMode": {
          "enum": [
            "compulsory flash firing",
            "compulsory flash suppression",
            "auto mode"
          ]
        },
        "FlashRedEyeMode": {
          "type": "boolean"
        },
        "FlashReturn": {
          "enum": [
            "no strobe return detection",
            "strobe return light not detected",
            "strobe return light detected"
          ]
        },
        "FocalLength": {
          "$ref": "#/definitions/rational"
        },
        "FocalLengthIn35mmFilm": {
          "type": "integer"
        },
        "ISOSpeedRatings": {
          "type": "integer"
        },
        "LightSource": {
          "enum": [
            "unknown",
            "daylight",
            "fluorescent",
            "tungsten",
            "flash",
            "fine weather",
            "cloudy weather",
            "shade",
            "daylight fluorescent",
            "day white fluorescent",
            "cool white fluorescent",
            "white fluorescent",
            "standard light a",
            "standard light b",
            "standard light c",
            "d55",
            "d65",
            "d75",
            "d50",
            "iso studio tungsten",
            "other"
          ]
        },
        "MaxApertureValue": {
          "$ref": "#/definitions/rational"
        },
        "MeteringMode": {
          "enum": [
            "unknown",
            "average",
            "centerweightedaverage",
            "spot",
            "multispot",
            "pattern",
            "partial",
            "other"
          ]
        },
        "ShutterSpeedValue": {
          "$ref": "#/definitions/rational"
        },
        "SubjectDistance": {
          "oneOf": [
            {
              "$ref": "#/definitions/rational"
            },
            {
              "enum": [
                "unknown",
                "infinite"
              ]
            }
          ]
        },
        "UserComment": {
          "type": "string"
        }
      },
      "additionalProperties": false,
      "minProperties": 1
    },
    "iptcCore": {
      "type": "object",
      "properties": {
        "CountryCode": {
          "type": "string"
        },
        "Location": {
          "type": "string"
        }
      },
      "additionalProperties": false,
      "minProperties": 1
    },
    "photoshop": {
      "type": "object",
      "properties": {
        "DateCreated": {
          "$ref": "#/definitions/xmpDateTime"
        },
        "City": {
          "type": "string"
        },
        "Country": {
          "type": "string"
        },
        "State": {
          "type": "string"
        }
      },
      "additionalProperties": false,
      "minProperties": 1
    },
    "tiff": {
      "type": "object",
      "properties": {
        "Make": {
          "type": "string"
        },
        "Model": {
          "type": "string"
        },
        "Orientation": {
          "enum": [
            "not defined",
            "top left",
            "top right",
            "bottom right",
            "bottom left",
            "left top",
            "right top",
            "right bottom",
            "left bottom"
          ]
        }
      },
      "additionalProperties": false,
      "minProperties": 1
    },
    "xmp": {
      "type": "object",
      "properties": {
        "CreateDate": {
          "$ref": "#/definitions/xmpDateTime"
        },
        "CreatorTool": {
          "type": "string"
        },
        "Label": {
          "type": "string"
        },
        "ModifyDate": {
          "$ref": "#/definitions/xmpDateTime"
        }
      },
      "additionalProperties": false,
      "minProperties": 1
    },
    "xmpMM": {
      "type": "object",
      "properties": {
        "DerivedFromDocument": {
          "type": "string"
        },
        "DerivedFromInstance": {
          "type": "string"
        }
      },
      "additionalProperties": false,
      "minProperties": 1
    },
    "xmpRights": {
      "type": "object",
      "properties": {
        "Marked": {
          "type": "boolean"
        },
        "UsageTerms": {
          "type": "string"
        },
        "WebStatement": {
          "type": "string"
        }
      },
      "additionalProperties": false,
      "minProperties": 1
    },
    "GPano": {
      "type": "object",
      "properties": {
        "UsePanoramaViewer": {
          "type": "boolean"
        },
        "ProjectionType": {
          "type": "string"
        },
        "CroppedAreaLeftPixels": {
          "type": "integer"
        },
        "CroppedAreaTopPixels": {
          "type": "integer"
        },
        "CroppedAreaImageWidthPixels": {
          "type": "integer"
        },
        "CroppedAreaImageHeightPixels": {
          "type": "integer"
        },
        "FullPanoWidthPixels": {
          "type": "integer"
        },
        "FullPanoHeightPixels": {
          "type": "integer"
        }
      },
      "additionalProperties": false,
      "minProperties": 1
    },
    "mwg-rs": {
      "type": "object",
      "properties": {
        "Regions": {
          "type": "object",
          "properties": {
            "AppliedToDimensions": {
              "type": "object",
              "properties": {
                "w": {
                  "type": "number"
                },
                "h": {
                  "type": "number"
                },
                "unit": {
                  "enum": [
                    "pixel"
                  ]
                }
              },
              "additionalProperties": false,
              "required": [
                "w",
                "h",
                "unit"
              ]
            },
            "RegionList": {
              "type": "array",
              "items": {
                "type": "object",
                "properties": {
                  "Area": {
                    "$ref": "#/definitions/rsArea"
                  },
                  "Type": {
                    "enum": [
                      "Face",
                      "Pet",
                      "Focus",
                      "BarCode"
                    ]
                  },
                  "Name": {
                    "type": "string"
                  },
                  "Description": {
                    "type": "string"
                  },
                  "FocusUsage": {
                    "enum": [
                      "EvaluatedUsed",
                      "EvaluatedNotUsed",
                      "NotEvaluatedNotUsed"
                    ]
                  },
                  "BarCodeValue": {
                    "type": "string"
                  },
                  "Extensions": {
                    "type": "object",
                    "properties": {
                      "adobe-fi": {
                        "$ref": "#/definitions/adobe-fi"
                      }
                    },
                    "additionalProperties": false,
                    "minProperties": 1
                  }
                },
                "required": [
                  "Area"
                ],
                "additionalProperties": false
              },
              "minItems": 1
            }
          },
          "additionalProperties": false,
          "minProperties": 1
        }
      },
      "additionalProperties": false,
      "minProperties": 1
    }
  },
  "additionalProperties": false,
  "minProperties": 1
}
]]

--------------------------------------------------------------------------------

function string.starts( str, start)

   return string.sub( str, 1, string.len( start ) ) == start
   
end

--------------------------------------------------------------------------------

function WFJsonValidatorTest.rxTestInvalidArguments( rxTest )

	rxTest:expectSpecificError( "bad argument #2 to 'createForSchema' (string expected, got number)", 
		function()
		
			WFJsonValidator.createForSchema( 1 )
		
		end )

	rxTest:expectSpecificError( "wrong number of arguments to createForSchema (schema string expected)", 
		function()
		
			WFJsonValidator.createForSchema( "foo", 2 )
		
		end )

end

--------------------------------------------------------------------------------

function WFJsonValidatorTest.rxTestInvalidJson( rxTest )
 
	rxTest:expectSpecificError( "error parsing schema", 
		function()
		
			WFJsonValidator.createForSchema( "foo" )
		
		end )

	local validator = WFJsonValidator.createForSchema( xmpSchema )
	
	rxTest:expectEqual({ 
			type = "jsonError", 
		},
		validator:validate( "bar" ) )
	
end

-------------------------------------------------------------------------------

function WFJsonValidatorTest.rxTestXmpSchema( rxTest )

	local xmp = [[
 	{
		"aux": {
			"ApproximateFocusDistance": [ 11, 3 ]
		},
        "exif": {
            "ApertureValue": [ 16, 1 ],
            "ExposureTime": [ 1, 200 ],
            "FNumber": [ 4, 1 ],
            "FocalLength": [ 90, 1 ],
            "ISOSpeedRatings": [ 100 ]
        },
        "tiff": {
            "Make": "Canon",
            "Model": "Canon EOS 5D Mark II"
        },
        "xmp": {
            "CreatorTool": "Adobe Camera"
        },
        "xmpRights": {
            "Marked": true,
            "UsageTerms": "Usage terms text here",
            "WebStatement": "http://myrightsstatement"
        }
    }
	]]

	local validator = WFJsonValidator.createForSchema( xmpSchema )

	local result = validator:validate( xmp )
	
	rxTest:expectEqual( "validationError", result.type )
	
	rxTest:expectEqual( {
			{
				description = "exif.ISOSpeedRatings: incorrect type",
				path = "exif.ISOSpeedRatings",
			},
		},
		result.errors )
	
end

--------------------------------------------------------------------------------

function WFJsonValidatorTest.rxTestSchemaDefinitions( rxTest )

	local schema = [[ 
		{
		  "$schema": "http://json-schema.org/draft-04/schema#iso8601-date-time",
		  "title": "valijson definitions schema",
		  "type": "object",
		  "definitions": {
			"rational": {
			  "type": "array",
			  "minItems": 2,
			  "maxItems": 2,
			  "items": {
				"type": "integer"
			  }
			}
		  },
		  "properties": {
			"rationalValue": {
			  "$ref": "#/definitions/rational"
			}
		  },
		  "additionalProperties": false,
		  "minProperties": 1
		}
	]]

	local rational = [[	{ "rationalValue": [1, 2, 3] } ]]

	local validator = WFJsonValidator.createForSchema( schema )

	local result = validator:validate( rational )

	rxTest:expectEqual( result.type, "validationError" )
		
	rxTest:expectEqual(	{
		{
				description = "rationalValue: maximum number of items exceeded",
				path = "rationalValue",
			}
		}, 
		result.errors )
	
	rational = [[	{ "rationalValue": [1, 2] } ]]

	rxTest:expectEqual( nil, validator:validate( rational ) )
	
end


--------------------------------------------------------------------------------

return WFRxTestCase.wrapSuite( WFJsonValidatorTest )
